How to pass optional parameters in url, via path () function?
Asked Answered
S

1

7

I'm confused about passing optional parameter via url in Django with path() instead of url(). I found that I should use kwargs, so I added it to path:

path('all/<str:category>/<int:page_num>/', views.show_all_objects, name="show-all-objects"),

to

path('all/<str:category>/<int:page_num>/', views.show_all_objects, kwargs={'city': None}, name="show-all-objects"),

Ok but now how to pass additional parameter from template, I tried with:

<a href="{% url 'show-all-objects' category='restaurants' page_num=1 city=1 %}"

which returns me common error for NoReverseMatch at /

So I added it to url:

path('all/<str:category>/<int:page_num>/<int:city>/', views.show_all_objects, kwargs={'city': None}, name="show-all-objects"),

But error is the same, I'm pretty sure, that this is not the proper way to do it, but I cannot find info about passing optional parameter via path(), all info is with url() Is it possible ?

Surprisal answered 21/11, 2019 at 15:48 Comment(1)
Have you tried a session variable?Rubellite
A
16

I have got one solution/workaround.

What you need to do is, define N different path configuration in urls.py, where N is the number of optional parameters

#urls.py
urlpatterns = [
                  path('foo/<param_1>/<param_2>/', sample_view, name='view-with-optional-params'),
                  path('foo/<param_1>/', sample_view, name='view-with-optional-params'),
                  path('foo/', sample_view, name='view-with-optional-params'),

              ]
#views.py
from django.http.response import HttpResponse


def sample_view(request, param_1=None, param_2=None):
    return HttpResponse("got response, param_1 is {} and param_2 is {}".format(param_1, param_2))

# template.html
<body>
<a href= {% url 'view-with-optional-params'  param_1='foo' param_2=123 %}>two parameters</a><br>
<a href= {% url 'view-with-optional-params'  param_1='foo' %}>one parameter</a><br>
<a href= {% url 'view-with-optional-params' %}>without parameter</a><br>
</body>
Airliah answered 21/11, 2019 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.