简体   繁体   English

Django反向URL在模板中带有可选参数

[英]Django reverse url with optional arguments in template

In my django project I have a simple url 在我的Django项目中,我有一个简单的网址

url(r'^report/(?P<slug>[\w-]+)/$', views.Report.as_view(), name='report')

I have placed this particular url at the bottom of my url file for the app. 我已将此特定网址放置在该应用程序的url文件的底部。 The slug field is an optional argument which may or may not be supplied as part of request. 子段字段是可选参数,可以作为请求的一部分提供,也可以不作为请求的一部分提供。

Now, in a template when I refer to this url with this syntax {% url 'appname:report' %} I get an NoReverseMatch found error. 现在,在模板中,当我使用此语法{% url 'appname:report' %} url'appname {% url 'appname:report' %}引用此url时,出现NoReverseMatch发现错误。 I have tried same thing in another app and it works fine. 我在另一个应用程序中尝试过同样的事情,并且效果很好。 Can anyone point out the probable cause for such behavior? 谁能指出这种行为的可能原因? I know I can have two separate urls but if it can be done using one, I would prefer it. 我知道我可以有两个单独的网址,但是如果可以使用一个网址,我会更喜欢它。

You are getting the error becayse slug is a required group in your regex. 因为正则表达式中的必需组slug所以您会收到错误消息。

r'^report/(?P<slug>[\w-]+)/$

I believe that you can make it work by wrapping slug in a non capturing group and making it optional. 我相信您可以通过将slug包装在一个非捕获组中并使其可选来使其工作。

r'^report/(?:(?P<slug>[\w-]+)?)/$

Personally, I find it clearer to have two entries in urls.py. 就个人而言,我发现在urls.py中有两个条目更为清晰。

url(r'^report/(?P<slug>[\w-]+)/$', views.Report.as_view(), name='report')
url(r'^report/$', views.Report.as_view(), name='report')

You don't need to mention the app name. 您无需提及应用名称。 Named urls are used to differ urls among different apps. 命名的URL用于在不同的应用程序之间不同的URL。 Try 尝试

{% url 'report' %}

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

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