简体   繁体   中英

Django Reverse URL Lookup Template Error

I'm having a bit of trouble with reverse URL lookups in Django.

From the template:

<form action="{% url 'blog:save' post.slug %}" method="post">

From urls:

url(r'^post/(?P<slug>\w+)/save/$', views.save, name='save'),

From views:

def save(request, slug):
    return HttpResponse("Not Saved.")

Error I'm getting:

Exception Type: NoReverseMatch
Exception Value:
Reverse for 'save' with arguments '(u'',)' and keyword arguments '{}' not found.

post.slug variable in your template is an empty string, but your url requires 1 or more characters ( \\w+ ). So Django builds /post//save/ , but this url is invalid.

If you need to save a new post with no slug, use an optional subpattern in url:

r'^post/(?:(?P<slug>\w+)/)?save/'

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