URL to work with parameter and without parameter in Django

Viewed 176

I am using Django for my project, and I want to render thank-you page. But it should be with or without parameters.

urls.py

urlpatterns = [
    ....
    path(r'thank-you?t=<type>?n=<name>', thank_you_view, name='thank-you'),
    ....
]

it is working fine for urls like :http://127.0.0.1:8080/thank-you%3Ft=teacher%3Fn=Ajay,%20Gaikwad Template make use of parameters.

but not working for url without parameters like : http://127.0.0.1:8080/thank-you Default template will be rendered here.

also I tried some regex

path(r'thank-you(?t=<type>?n=<name>|'')', thank_you_view, name='thank-you'), But it not working.


If you use below view and render context with template then it will work.

views.py

def thank_you_view(request, *args, **kwargs):
    context = {kwargs['type']: kwargs['name']}
    return render(request, "light/thank-you.html", context=context)

Edit:

  • Is it any way to use regex in url so it will work for both ways?
  • Or can we make parameters as optional?
1 Answers

Once you define path parameters, Django is expecting it in the URL. Else you can get it as query parameters. You're mixing up query and path parameters.

Related