Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django URLs - How to pass a list of items via clean URLs?

Tags:

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?

like image 277
letoosh Avatar asked Mar 02 '10 00:03

letoosh


People also ask

What is dynamic URL in Django?

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.

What does the Django urls reverse () function do?

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.

What is slug in Django urls?

A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs."


1 Answers

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
    #...
like image 200
Amitay Dobo Avatar answered Oct 11 '22 17:10

Amitay Dobo