开发者

Django URL pattern with a list

开发者 https://www.devze.com 2023-03-11 05:09 出处:网络
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:

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'),开发者_StackOverflow中文版

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

Thanks, Meir


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'),


As URL matching is done based on a regular expression you can use the ability of regular expressions to match multiple strings to do this. The | (pipe) character selects between multiple options, i.e. (a|b|c) will match a, b or c.

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

The Python regular expression documentation is really rather good and worth a read.


For Django 2+ with Python 3+, you can use the following:

from django.urls import re_path
from . import views

# List of category names defined here:
_entities = ["tv", "movie", "theater"]
re_entities = f'(?P<enertainment>{"|".join(_entities)})'

urlpatterns = [
    ...
    re_path(f'^{re_entities}/.../$', views.EntertainmentHandler.as_view()),
    ...
    ]
0

精彩评论

暂无评论...
验证码 换一张
取 消