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

2

7

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?

Flagg answered 2/3, 2010 at 0:40 Comment(0)
F
5

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
    #...
Frias answered 2/3, 2010 at 1:54 Comment(2)
Just noticed it duplicates #249610 , but perhaps someone will find the regexp useful.Frias
Thanks a lot. Unfortunately I couldn't find this one when posting my question. The regexp is great, thanks.Flagg
I
1

you can create custom path converter

create converts.py and add to it ListCoverter class:

class ListConverter:
    #  return any combination of '/folder1/folder2'
    regex = '.*\/*'

    def to_python(self, folder_list):
        return folder_list.split('/')
        

    def to_url(self, folder_list):
        return folder_list

make sure to pass the list as an argument to folder_view and folder_delete functions in view.py file

in urls.py you need to register this converter:

from django.urls import path, register_converter
from . import views, converts


register_converter(converts.ListConverter, 'list')

path('<list:folder_name>/view', views.folder_View)
Iseult answered 18/3, 2023 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.