[Answered ]-Django URL logical OR misunderstood

0πŸ‘

βœ…

As error message says, the view need 2 arguments, but you have declared one. That another argument will be your readme or help.

So for solving it, you can use *args:

def readme(request, *args, **kwargs):
    return HttpResponse('My test', content_type='text/plain')

Or if you want the readme or help in your view, you can have it as just argument:

def readme(request, selected_url):
    return HttpResponse('My test', content_type='text/plain')
πŸ‘€Amin

1πŸ‘

You are working with a capture group and pass this as the first item, so it will pass a string readme or help, so you can work with:

def readme(request, item):
    # item will be 'readme' or 'help'
    return HttpResponse('My test', content_type='text/plain')


urlpatterns = [
    re_path(r'^(readme|help)/$', readme),
]

It is however more elegant to define just two paths:

def readme(request):  # πŸ–˜ no item
    return HttpResponse('My test', content_type='text/plain')


urlpatterns = [
    path('readme/', readme),
    path('help/', readme),
]

and while not invalid, usually using two paths to point to the same "resource" is not considered good design. Usually you want that two different paths point to different information.

Or if you want to use it with an optional parameter:

def readme(request, lang):
    # …
    pass


inner_urls = [path('readme/', readme), path('help/', readme)]

urlpatterns = [
    path('/', include(inner_urls), kwargs={'lang': None}),
    re_path(r'^(?P<lang>en)/$', include(inner_urls)),
]

This will pass en to lang, or None if it was not "picked".

If you however want to pick a language, you likely want to use i18n_patterns(…)Β [Django-doc], which is Django’s internationalization solution for multi-language sites.

Leave a comment