Search code examples
pythonregexurl-routingdjango-2.0

How to put limitation on url patterns in Django 2


Django 1.11 uses regular expression to check for appropriate url. eg

url(r'^(?P<year>[0-9]{4})/$', views.abc),

Here I could check that my year is 4 digits.

The new way introduced is like

path('<int:year>/', views.abc),

Is there a default way to use restrictions using path()?


Solution

  • Directly lifted from the Django Docs

    You can define your custom converters:

    class FourDigitYearConverter:
        regex = '[0-9]{4}'
    
        def to_python(self, value):
            return int(value)
    
        def to_url(self, value):
            return '%04d' % value
    

    Then:

    from django.urls import register_converter, path
    
    from . import converters, views
    
    register_converter(converters.FourDigitYearConverter, 'yyyy')
    
    urlpatterns = [
        path('articles/2003/', views.special_case_2003),
        path('articles/<yyyy:year>/', views.year_archive),
        ...
    ]