Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

django - Recursive URL Patterns CMS Style

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...