views:

326

answers:

1

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.

+4  A: 

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.

Achimnol
Thank you. Much appreciated!
bkorte