Django反向URL查找模板错误

时间:2013-08-15 20:10:44

标签: python django templates

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

1 个答案:

答案 0 :(得分:3)

模板中的

post.slug变量为空字符串,但您的网址需要1个或多个字符(\w+)。所以Django构建/post//save/,但这个url无效。

如果您需要保存没有slug的新帖子,请在url中使用可选的子模式:

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