Django模板NoReverseMatch异常

时间:2013-08-11 00:55:25

标签: django django-templates django-views

我正在尝试在django 1.5中创建一个博客。我收到此异常消息Reverse for 'blog.views.add_comment post.id' with arguments '(4,)' and keyword arguments '{}' not found.我看不出问题出在哪里。模板代码如下。

...
    <!-- post.html -->
       <form action="{% url 'blog.views.add_comment' post.id %}" method="POST">{% csrf_token %}
        <div id="cform">
        Name: {{ form.author }}
        <p>{{ form.body|linebreaks }}</p>
         </div>
        <div id="submit"><input type="submit" value="Submit"></div>
        </form>
...

这是我blog.view.py

中的代码
@render_to('post.html')
def post_detail(request, pk):
    post = Post.objects.get(pk=int(pk))
    comments = Comment.objects.filter(post = post)
    dic = {'post': post, 'user': request.user, 'comments': comments, 'form': CommentForm()}
    dic.update(csrf(request))
    return dic


def add_comment(request, pk):
    """add new comment"""
    p = request.POST

    if p.has_key('body') and p['body']:
        author = 'anonymus'
        if p['author']:
            author = p['author']

        comment = Comment (post=Post.objects.get(pk=pk))
        cf = CommentForm(p, instace = comment)
        cf.fields['author'].required = False

        comment = cf.save(commit = False)
        comment.author = author
        comment.save()
    return HttpResponseRedirect(reverse('views.post_detail', args=[pk]))

最后是我的blog.urls.py

urlpatterns = patterns('blog.views',
url(r'^$', 'main'),
...
    url(r'^add_comment/(?P<pk>\d+)/$', 'add_comment'),
)

现在已经修复了丢失的'关键字'谢谢

1 个答案:

答案 0 :(得分:2)

试试这个:

{% url 'blog.views.add_comment' post.id %}