Django URLs - How do I pass a list of items through pure URLs?

I need to implement a structure like this: example.com/folder1/folder2/folder3/../view (there may be other things in the end instead of "view")

The depth of this structure is unknown, and there may be a folder deeply immersed in a tree. It is very important to get this exact URL pattern, i.e. I can't just go to example.com/folder_id

Any ideas on how to implement this using Django's URL Manager?

+4
source share
1 answer

The Django url dispatcher is based on regular expressions, so you can provide it with a regular expression that will match the desired path (with duplicate groups). However, I could not find a way to force django url dispatcher to correspond to several subgroups (it returns only the last match as a parameter), so part of the processing of the parameters remains for presentation.

Here is an example url template:

urlpatterns = patterns('', #... (r'^(?P<foldersPath>(?:\w+/)+)(?P<action>\w+)', 'views.folder'), ) 

In the first parameter, we have a group that does not capture the entry for repeating "word" characters, followed by "/". You might want to change \ w to another to include characters other than alphabet and numbers.

you can, of course, change it to several types in the URL configuration instead of using the action parameter (which is more important 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 break the first parameter to get an array of folders:

 def folder(request, foldersPath, action): folders = foldersPath.split("/")[:-1] print "folders:", folders, "action:", action #... 
+5
source

Source: https://habr.com/ru/post/1302822/


All Articles