Search code examples
pythondjangourl-pattern

URL pattern in django to match limited set of words


I have a URL pattern in Django where there is a variable (called name) that should only take one of a select list of words. Something like this:

path("profile/<marta|jose|felipe|manuela:name>/", views.profile),

So basically only these paths are valid:

  • profile/marta/
  • profile/jose/
  • profile/felipe/
  • profile/manuela/

How exactly can I configure this in the Django url patterns? The above syntax tries to illustrate the idea but doesn't work. I've seen this ten year old question but that uses the previous format in the url patterns file so I imagine it should be done differently now...?


Solution

  • Why not put them in view?

    from django.http import Http404
    
    def profiles(request, name):
        if not name in ['marta', 'jose', 'felipe', 'manuela']:
            raise Http404('You shall not pass!')
    

    Or you can simply use re_path:

    urlpatterns = [
        re_path(r'^profile/(?P<name>marta|jose|felipe|manuela)/$', views.index, name='index'),
    ]