2

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

3 Answers 3

8

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'),
Sign up to request clarification or add additional context in comments.

1 Comment

If you also want to pass the category to the view as a named parameter: url(r'^site/(?P<category>tv|movie|theater)/$', 'mainsite.views.home')
5

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.

Comments

2

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()),
    ...
    ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.