Enable sluggified URLs in Django

Peter Horne picture Peter Horne · Oct 25, 2009 · Viewed 10.6k times · Source

I am trying to enable sluggified URLs in Django of the form that SO uses: example.com/id/slug. I have no problem enabling slugs, and have URLs currently set up of the form: http://127.0.0.1:8000/articles/id/ (eg. /articles/1/) and that works fine. The corresponding URLpattern is:

(r'^(?P<object_id>\d+)/$',  'django.views.generic.list_detail.object_detail', info_dict),

If I change the URL pattern to:

(r'^(?P<slug>\d+)/$',  'django.views.generic.list_detail.object_detail', info_dict),

Then I recieve the following eror when I navigate to http://127.0.0.1:8000/articles/another-article/:

The current URL, articles/another-article/, didn't match any of these.

If, however, I try:

http://127.0.0.1:8000/articles/1/

I get the error:

No article found matching the query

Ultimately I want to be able to navigate to an aricle via either:

http://127.0.0.1:8000/articles/1/ or http://127.0.0.1:8000/articles/1/another-article/

Answer

Peter Horne picture Peter Horne · Oct 25, 2009

I should have been just a little more patient before asking this question because I figured out the answer:

(r'^(?P<object_id>\d+)/$',  'django.views.generic.list_detail.object_detail', info_dict),
(r'^(?P<object_id>\d+)/(?P<slug>[-\w]+)/$',  'django.views.generic.list_detail.object_detail', info_dict),

The first pattern allows URLs of the form /articles/1/ which means that the second urlpattern (to include the slug) is optional.