Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 2 url path matching negative value

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()?

like image 707
Paullo Avatar asked Feb 19 '18 14:02

Paullo


People also ask

What happens when a URL is matched Django?

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).

Is URL and path same in Django?

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.

Is URL deprecated in Django?

Yes, if they upgrade to django-4.0, url will no longer be available.

What happens if you skip trailing slash in Django?

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.


1 Answers

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),
    ...
]
like image 115
neverwalkaloner Avatar answered Sep 30 '22 18:09

neverwalkaloner