带有列表的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'),更多推荐
发布评论