Django URL - 如何通过干净的 URL 传递项目列表? [英] Django URLs - How to pass a list of items via clean URLs?
问题描述
我需要实现一个类似于这样的结构:example.com/folder1/folder2/folder3/../view(最后可以有其他东西而不是视图")
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")
这个结构的深度未知,可能有一个文件夹埋在树深处.获得这个确切的 URL 模式是必不可少的,即我不能只去 example.com/folder_id
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
有关如何使用 Django URL 调度程序实现此功能的任何想法?
Any ideas on how to implement this with the Django URL dispatcher?
推荐答案
Django 的 url 调度程序基于正则表达式,因此您可以为它提供一个与您想要的路径(带有重复组)匹配的正则表达式.但是我没找到让django的url dispatcher匹配多个子组的方法(它只返回最后一个匹配作为参数),所以部分参数处理留给view处理.
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'),
)
在第一个参数中,我们有一个非捕获组,用于重复后跟/"的单词"字符.也许您想将 \w 更改为其他内容以包含字母和数字以外的其他字符.
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.
您当然可以在 url 配置中将其更改为多个视图,而不是使用 action 参数(如果您的操作集有限,这更有意义):
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
#...
这篇关于Django URL - 如何通过干净的 URL 传递项目列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!