views:

184

answers:

1

Hi all,

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?

A: 

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
    #...
Amitay Dobo
Just noticed it duplicates http://stackoverflow.com/questions/249110/django-arbitrary-number-of-unnamed-urls-py-parameters , but perhaps someone will find the regexp useful.
Amitay Dobo
Thanks a lot. Unfortunately I couldn't find this one when posting my question. The regexp is great, thanks.
Alex Letoosh