开发者

Enable sluggified URLs in Django

开发者 https://www.devze.com 2022-12-09 04:06 出处:网络
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

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/


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消