Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Whenever I learn a new language/framework, I always make a content management system...

I'm learning Python & Django and I'm stuck with making a URL pattern that will pick the right page.

For example, for a single-level URL pattern, I have:

url(r'^(?P<segment>[-w]+)/$', views.page_by_slug, name='pg_slug'),

Which works great for urls like:

http://localhost:8000/page/

Now, I'm not sure if I can get Django's URL system to bring back a list of slugs ala:

http://localhost:8000/parent/child/grandchild/

would return parent, child, grandchild.

So is this something that Django does already? Or do I modify my original URL pattern to allow slashes and extract the URL data there?

Thanks for the help in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

That's because your regular expression does not allow middle '/' characters. Recursive definition of url segments pattern may be possible, but anyway it would be passed as a chunk to your view function.

Try this

url(r'^(?P<segments>[-/w]+)/$', views.page_by_slug, name='pg_slug'),

and split segments argument passed to page_by_slug() by '/', then you will get ['parent', 'child', 'grandchild']. I'm not sure how you've organized the page model, but if it is not much sophiscated, consider using or improving flatpages package that is already included in Django.

Note that if you have other kind of urls that does not indicate user-generated pages but system's own pages, you should put them before the pattern you listed because Django's url matching mechanism follows the given order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...