I need to implement a structure similar to this: example.com/folder1/folder2/folder3/../view (there can be other things at the end instead of "view")
The depth of this structure is not known, and there can be a folder buried deep inside the tree. It is essential to get this exact URL pattern, i.e. I cannot just go for example.com/folder_id
Any ideas on how to implement this with the Django URL dispatcher?
Being able to capture one or more values from a given URL during an HTTP request is an important feature Django offers developers. We already saw a little bit about how Django routing works, but those examples used hard-coded URL patterns. While this does work, it does not scale.
the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here.
A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs."
Django's url dispatcher is based on regular expressions, so you can supply it with a regex that will match the path you wanted (with repeating groups). However, I couldn't find a way to make django's url dispatcher match multiple sub-groups (it returns only the last match as a parameter), so some of the parameter processing is left for the view.
Here is an example url pattern:
urlpatterns = patterns('',
#...
(r'^(?P<foldersPath>(?:\w+/)+)(?P<action>\w+)', 'views.folder'),
)
In the first parameter we have a non-capturing group for repeating "word" characters followed by "/". Perhaps you'd want to change \w to something else to include other characters than alphabet and digits.
you can of course change it to multiple views in the url configuration instead of using the action param (which makes more sense if you have a limited set of actions):
urlpatterns = patterns('',
#...
(r'^(?P<foldersPath>(?:\w+/)+)view', 'views.folder_View'),
(r'^(?P<foldersPath>(?:\w+/)+)delete', 'views.folder_delete'),
)
and in the views, we split the first parameter to get an array of the folders:
def folder(request, foldersPath, action):
folders = foldersPath.split("/")[:-1]
print "folders:", folders, "action:", action
#...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With