简体   繁体   中英

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

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM