Regular expression in URL for Django slug

前端 未结 3 521
轻奢々
轻奢々 2020-12-17 10:44

I have 2 URL\'s with a slug field in the URL.

url(r\'^genres/(?P.+)/$\', views.genre_view, name=\'genre_view\'),
url(r\'^genres/(?P.+         


        
3条回答
  •  渐次进展
    2020-12-17 11:28

    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[-\w]+)/$', views.genre_view, name='genre_view'),
    url(r'^genres/(?P[-\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//', views.genre_view, name='genre_view'),
    path('genres//monthly/', views.genre_month, name='genre_month'),
    

提交回复
热议问题