Reputation: 3502
I was wondering if there is a way in Django to have urls that allow multiple arguments after the /, a variable amount of them.
Here is an example of what I mean:
So if I have a page called about us with a url /page/about_us then I have a page linked from about us called contact info, would it's url be /page/about_us/contact_info which might have another page under it and so on.
How would you write URL processing to allow /page followed by any number of other pages with slashes between? This seems like it would be useful for doing things like bread crumbs and also would make the urls very readable. I just don't know how I would make the regex or a view that can take the variable number pages in the path as arguments.
Would it be best to just use a regex that captures everything after /page/ as one long parameter and then have the view break it down by splitting at the /'s? What would such a regex look like? I don't seem to be able to include a / in a regex without issues.
Upvotes: 2
Views: 2666
Reputation: 39287
One way to do this with your urls.py is to terminate your regex with $
or watch the order that your urls are added.
For example:
url(r'^page/about_us/$', 'example.views.about_us', name='about_us'),
url(r'^page/about_us/contact_info/$', 'example.views.contact_info', name='contact_info'),
url(r'^page/about_us/contact_info/map/$', 'example.views.map', name='map'),
would work correctly. So would:
url(r'^page/about_us/contact_info/map/', 'example.views.map', name='map'),
url(r'^page/about_us/contact_info/', 'example.views.contact_info', name='contact_info'),
url(r'^page/about_us/', 'example.views.about_us', name='about_us'),
But this wouldn't let you reach pages other than your about_us page:
url(r'^page/about_us/', 'example.views.about_us', name='about_us'),
url(r'^page/about_us/contact_info/', 'example.views.contact_info', name='contact_info'),
url(r'^page/about_us/contact_info/map/', 'example.views.map', name='map'),
In the last example, if your site was located at www.example.com
and you went to www.example.com/page/about_us/
you would reach the about_us view. However, if you went to www.example.com/page/about_us/contact_us/
you would still reach the about_us view. This is because if your regex doesn't end with a $
, it will match anything that starts with your expression and redirect you.
The url's are checked in order so if you do leave off the $
and the order of the urls are added appropriately you will still reach the correct pages, as in the second block of urls.
Upvotes: 5