简体   繁体   中英

Django reverse url with optional arguments in template

In my django project I have a simple url

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

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.

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

Personally, I find it clearer to have two entries in 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. Try

{% url 'report' %}

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