2015-03-02 77 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