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 ?

1
  • Have you tried a session variable? Commented Nov 21, 2019 at 16:09

1 Answer 1

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

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.