Django URL - 如何通过干净的 URL 传递项目列表?
我需要实现与此类似的结构: example.com/folder1/folder2/folder3/../view (末尾可以有其他内容而不是“view”
)结构未知,并且可能有一个文件夹埋在树的深处。获得这个精确的 URL 模式至关重要,即我不能只使用 example.com/folder_id
关于如何使用 Django URL 调度程序实现这一点有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django 的 url 调度程序基于正则表达式,因此您可以为其提供与您想要的路径(带有重复组)相匹配的正则表达式。
但是,我找不到一种方法让 django 的 url 调度程序匹配多个子组(它只返回最后一个匹配作为参数),因此一些参数处理留给了视图。
下面是一个 url 模式示例:
在第一个参数中,我们有一个非捕获组,用于重复“word”字符,后跟“/”。也许您想将 \w 更改为其他内容以包含字母和数字以外的其他字符。
当然,您可以在 url 配置中将其更改为多个视图,而不是使用操作参数(如果您的操作集有限,这更有意义):
并且在视图中,我们拆分第一个参数以获取数组文件夹:
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:
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):
and in the views, we split the first parameter to get an array of the folders:
您可以创建自定义路径转换器
创建converts.py并添加到其中ListCoverter类:
确保将列表作为参数传递给
urls.py中view.py文件中的folder_view和folder_delete函数,您需要注册此转换器:
you can create custom path converter
create converts.py and add to it ListCoverter class:
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: