django urls 参数数量可变
我想知道 Django 中是否有一种方法可以让 url 允许在 / 之后有多个参数,其中参数的数量是可变的。
这是我的意思的一个例子:
所以,如果我有一个名为“关于我们”的页面,其 url /page/about_us 那么我有一个从“关于我们”链接到的页面,称为“联系信息”,那么它的 url 可能是 /page/about_us/contact_info下面还有另一页,依此类推。
您将如何编写 URL 处理以允许 /page 后跟任意数量的其他页面,中间有斜杠?这似乎对于做面包屑之类的事情很有用,而且还可以使网址非常可读。我只是不知道如何制作正则表达式或视图,可以将路径中的可变页数作为参数。
最好只使用一个正则表达式来捕获 /page/ 之后的所有内容作为一个长参数,然后让视图通过在 / 处拆分来分解它?这样的正则表达式会是什么样子?我似乎无法在正则表达式中包含 / 而不出现问题。
I was wondering if there is a way in Django to have urls that allow multiple arguments after the /, a variable amount of them.
Here is an example of what I mean:
So if I have a page called about us with a url /page/about_us then I have a page linked from about us called contact info, would it's url be /page/about_us/contact_info which might have another page under it and so on.
How would you write URL processing to allow /page followed by any number of other pages with slashes between? This seems like it would be useful for doing things like bread crumbs and also would make the urls very readable. I just don't know how I would make the regex or a view that can take the variable number pages in the path as arguments.
Would it be best to just use a regex that captures everything after /page/ as one long parameter and then have the view break it down by splitting at the /'s? What would such a regex look like? I don't seem to be able to include a / in a regex without issues.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 urls.py 执行此操作的一种方法是使用
$
终止正则表达式,或者观察 url 添加的顺序。例如:
可以正常工作。也是如此:
但这不会让您访问 about_us 页面以外的页面:
在上一个示例中,如果您的网站位于
www.example.com
并且您访问了www.example.com。 example.com/page/about_us/
您将到达 about_us 视图。但是,如果您访问www.example.com/page/about_us/contact_us/
,您仍然会到达 about_us 视图。这是因为如果您的正则表达式不以$
结尾,它将匹配以您的表达式开头的任何内容并重定向您。url 会按顺序检查,因此,如果您确实省略了
$
并且正确添加了 url 的顺序,您仍然会到达正确的页面,如第二个 url 块中所示。One way to do this with your urls.py is to terminate your regex with
$
or watch the order that your urls are added.For example:
would work correctly. So would:
But this wouldn't let you reach pages other than your about_us page:
In the last example, if your site was located at
www.example.com
and you went towww.example.com/page/about_us/
you would reach the about_us view. However, if you went towww.example.com/page/about_us/contact_us/
you would still reach the about_us view. This is because if your regex doesn't end with a$
, it will match anything that starts with your expression and redirect you.The url's are checked in order so if you do leave off the
$
and the order of the urls are added appropriately you will still reach the correct pages, as in the second block of urls.