In Django <2 the normal way of doing this is to use regex expression. But it is now recommended in Django => 2 to use path() instead of url()
path('account/<int:code>/', views.account_code, name='account-code')
This looks okay and works well matching url pattern
/account/23/
/account/3000/
However, this issue is that I also want this to match negative integer like
/account/-23/
Please how do I do this using path()?
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).
The path function is contained with the django. urls module within the Django project code base. path is used for routing URLs to the appropriate view functions within a Django application using the URL dispatcher.
Yes, if they upgrade to django-4.0, url will no longer be available.
If you're creting a RESTful API using Django, this can be a good solution when developers POST data directly to endpoint URL. When using APPEND_SLASH , if they accidently sent it without trailing slash, and your urlconf is WITH a trailing slash they would get an exception about data lose when redirecting POST requests.
You can write custom path converter:
class NegativeIntConverter:
regex = '-?\d+'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%d' % value
In urls.py:
from django.urls import register_converter, path
from . import converters, views
register_converter(converters.NegativeIntConverter, 'negint')
urlpatterns = [
path('account/<negint:code>/', views.account_code),
...
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With