评论未在帖子中显示

2024-04-20 13:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是刚到Django的,我想在我的细节中加入一些评论,但没有显示出来。以下是我的观点的相关部分

def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
                                status = 'published',
                                publish__year = year,
                                publish__month = month,
                                publish__day = day)
comments = post.comments.filter(active= True)
if request.method == 'POST':
    comment_form = CommentForm(data=request.POST)
    if comment_form.is_valid():
        new_comment = comment_form.save(commit=False)
        new_comment.post = post
        new_comment.save()
else:
    comment_form = CommentForm()
return render(request, 'detail.html', {'post':post})

这是models.py文件。我想问题出在我的观点文件上

class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments')
name = models.CharField(max_length=60)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)

class Meta:
    ordering = ('created',)

def __str__(self):
    return 'comment by {} on {}'.format(self.name, self.post)

这是my detail.html当您发现错误时请通知我

{% with comments.count as total_comments %}
<h2>
{{ total_comments }} comment{{ total_comments|pluralize }}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment {{ forloop.counter }} by {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.body|linebreaks }}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
<h2>Add a new comment</h2>
<form action="." method="POST">
    {{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endif %}
{% endblock %}

Tags: nameformtruenewmodelsrequestcommenth2