带有列表的Django URL模式(Django URL pattern with a list)

编程入门 行业动态 更新时间:2024-10-18 00:29:28
带有列表的Django URL模式(Django URL pattern with a list)

我有一个包含类别名称的列表,例如cats = ["tv", "movie", "theater"] 。 我想写一个url模式来只捕获包含列表中某个项的URL,例如:

url(r'^site/CATEGORY_NAME/$', 'mainsite.views.home'),

这样CATEGORY_NAME只能列出cat中的一个项目。 我怎样才能做到这一点?

谢谢,梅尔

I have a list with category names , e.g. cats = ["tv", "movie", "theater"]. I would like to write a url pattern to catch only URLs which contain one of the items in the list, such as:

url(r'^site/CATEGORY_NAME/$', 'mainsite.views.home'),

so that CATEGORY_NAME can only one one of the items in the list cats. How can I do that?

Thanks, Meir

最满意答案

您可以使用python的字符串join方法从列表中构建正则表达式的一部分,然后在URL模式中使用它。

例如:

cats = ["tv", "movie", "theater"] cats_re = '(?:' + '|'.join(cats) + ')' # ...then... url(r'^site/' + cats_re + '/$', 'mainsite.views.home'),

在这种情况下,整个正则表达式看起来像:

url(r'^site/(?:tv|movie|theater)/$', 'mainsite.views.home'),

You can build part of a regular expression from the list by using python's string join method, and then use that in the URL pattern.

For example:

cats = ["tv", "movie", "theater"] cats_re = '(?:' + '|'.join(cats) + ')' # ...then... url(r'^site/' + cats_re + '/$', 'mainsite.views.home'),

In this case, the whole regular expression would look like:

url(r'^site/(?:tv|movie|theater)/$', 'mainsite.views.home'),

更多推荐

本文发布于:2023-08-07 13:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   列表   Django   URL   pattern

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!