Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable sluggified URLs in Django

Tags:

url

django

slug

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/

like image 559
Peter Horne Avatar asked Oct 25 '09 12:10

Peter Horne


1 Answers

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.

like image 159
Peter Horne Avatar answered Sep 30 '22 04:09

Peter Horne