2015-03-02 78 views
3

我试着先看过不少帖子,而且他们都没有看到我的解决方案的答案(至少不是一个明显的答案)。我对Django仍然很陌生,所以我仍然掌握着一切(如模型,视图,表单等)。该博客最初是他们教程中的djangogirls博客的副本,但我想通过在网络上添加另一个教程的评论来扩展它。我遇到了一个我以后无法弄清楚的错误。如何修复django博客评论中的“NoReverseMatch”?

下面是注释的源代码:

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模式(网址.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的追踪是疯狂的Y,但第一点回到这一行views.py:

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

Django的哪个版本你使用? – PyDroid 2015-03-10 12:43:30

+0

我正在使用Django版本1.8.3 – tsujin 2015-08-27 02:43:51

回答

2

如果您正在使用新的Django 1.4,你需要引用您的add_comment

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

哇,像一个魅力工作,是一个惊人的简单修复。非常感谢,并感谢您的快速响应。只要计时器允许,我会尽快核对你的答案。 – tsujin 2015-03-02 06:11:47

+0

@Megalowhale没问题,很高兴帮助:) – 2015-03-02 06:17:58