如何修复" NoReverseMatch"在django博客评论?

时间:2015-03-02 06:03:04

标签: python django

我首先尝试查看了很多帖子,但他们似乎都没有找到我的解决方案的答案(至少不是一个明显的答案)。我对Django来说还是一个新手,所以我仍然对所有相关事项(模型,视图,表格等)都有所了解。该博客最初是他们教程中djangogirls博客的副本,但我想通过添加网络上另一个教程的评论来扩展它。我遇到了一个我以后无法弄清楚的错误。

以下是评论的源代码:

forms.py

class CommentForm(forms.ModelForm):
class Meta:
    model = Comment
    exclude = ["post"]

views.py

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)

    comments = Comment.objects.filter(post=post)
    d = dict(post=post, comments=comments, form=CommentForm(),
        user=request.user)
    d.update(csrf(request))
    return render_to_response('blog/post_detail.html', d)


def add_comment(request, pk):
    """Add a comment to a post."""
    p = request.POST
    if p.has_key("body") and p["body"]:
        author = "Anonymous"
        if p["author"]: author = p["author"]

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

        comment = cf.save(commit=False)
        comment.author = author
        comment.save()

    return redirect("dbe.blog.views.post_detail", args=[pk])

models.py

class Comment(models.Model):
    created_date = models.DateTimeField(auto_now_add=True)
    author = models.CharField(max_length=60)
    body = models.TextField()
    post = models.ForeignKey(Post)

def __unicode__(self):
    return unicode("%s: %s" % (self.post, self.body[:60]))

class CommentAdmin(admin.ModelAdmin):
    display_fields = ["post", "author", "created_date"]

url pattern(urls.py):

url(r'^add_comment/(\d+)/$', views.post_detail, name='add_comment')

post_detail.html:

<!-- Comments -->
{% if comments %}
    <p>Comments:</p>
{% endif %}

{% for comment in comments %}
    <div class="comment">
        <div class="time">{{ comment.created_date }} | {{ comment.author }}</div>
        <div class="body">{{ comment.body|linebreaks }}</div>
    </div>
{% endfor %}

<div id="addc">Add a comment</div>
<!-- Comment form -->
<form action="{% url 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>

{% endblock %}

错误是在post_detail.html中突出显示这一行:

<form action="{% url add_comment post.id %}" method="POST">{% csrf_token %}

错误本身说:

NoReverseMatch at /post/1/
Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

来自django的追溯是非常笨拙的,但它首先回到了views.py中的这一行:

    return render_to_response('blog/post_detail.html', d)

1 个答案:

答案 0 :(得分:2)

如果您使用的是比1.4更新的Django,则需要引用add_comment

<form action="{% url 'add_comment' post.id %}" method="POST">