简体   繁体   English

如何通过路径()function传递url中的可选参数?

[英]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() .我对使用path()而不是url()在 Django 中通过 url 传递可选参数感到困惑。 I found that I should use kwargs , so I added it to path:我发现我应该使用kwargs ,所以我将它添加到路径:

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 / NoReverseMatch at /常见错误

So I added it to url:所以我将它添加到 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?但是错误是一样的,我很确定,这不是正确的方法,但是我找不到有关通过path()传递可选参数的信息,所有信息都与url()可能吗?

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中定义N个不同的路径配置,其中N可选参数的个数

#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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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