[Fixed]-Regular expression in URL for Django slug

30๐Ÿ‘

โœ…

Django always uses the first pattern that matches. For urls similar to genres/genre_name/monthly your first pattern matches, so the second one is never used. The truth is the regex is not specific enough, allowing all characters โ€“ which doesnโ€™t seem to make sense.

You could reverse the order of those patterns, but what you should do is to make them more specific (compare: urls.py example in generic class-based views docs):

url(r'^genres/(?P<slug>[-\w]+)/$', views.genre_view, name='genre_view'),
url(r'^genres/(?P<slug>[-\w]+)/monthly/$', views.genre_month, name='genre_month'),

Edit 2020:

Those days (since Django 2.0), you can (and should) use path instead of url. It provides built-in path converters, including slug:

path('genres/<slug:slug>/', views.genre_view, name='genre_view'),
path('genres/<slug:slug>/monthly/', views.genre_month, name='genre_month'),
๐Ÿ‘คLudwik Trammer

11๐Ÿ‘

I believe that you can also drop the _ from the pattern that @Ludwik has suggested and revise to this version (which is one character simpler ๐Ÿ™‚ ):

url(r'^genres/(?P<slug>[-\w]+)/$', views.genre_view, name='genre_view'),
url(r'^genres/(?P<slug>[-\w]+)/monthly/$', views.genre_month, name='genre_month'),

Note that \w stands for โ€œword characterโ€œ. It always matches the ASCII characters [A-Za-z0-9_]. Notice the inclusion of the underscore and digits. more info

๐Ÿ‘คBabak K

5๐Ÿ‘

In Django >= 2.0, slug is included in URL by doing it like below.

from django.urls import path

urlpatterns = [
    ...
    path('articles/<slug:some_title>/', myapp.views.blog_detail, name='blog_detail'),
    ...
]

Source: https://docs.djangoproject.com/en/2.0/ref/urls/#django.urls.path

๐Ÿ‘คSuperNova

Leave a comment