我在 Django 中的反向 URL 查找方面遇到了一些麻烦。
来自模板:
<form action="{% url 'blog:save' post.slug %}" method="post">
来自网址:
url(r'^post/(?P<slug>\w+)/save/$', views.save, name='save'),
来自观点:
def save(request, slug):
return HttpResponse("Not Saved.")
我遇到的错误:
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'save' with arguments '(u'',)' and keyword arguments '{}' not found.
最佳答案
模板中的
post.slug
变量是空字符串,但您的网址需要 1 个或多个字符 (\w+
)。所以Django构建了/post//save/
,但是这个url是无效的。
如果您需要保存没有 slug 的新帖子,请在 url 中使用可选的子模式:
r'^post/(?:(?P<slug>\w+)/)?save/'
关于python - Django 反向 URL 查找模板错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260922/