在删除页面上显示评论内容

时间:2019-01-04 01:21:17

标签: python django templates

我无法在Django模板中显示评论内容。 我必须将某些东西传递给视图还是我只是以错误的方式调用对象?

views.py

def comment_delete(request, pk):
    comment = get_object_or_404(Comment, pk=pk)

    try:
        if request.method == 'POST':
            comment.delete()
            messages.success(request, 'You have successfully deleted the Comment')
            return redirect('post_detail', pk=comment.post.pk)
        else:
            template = 'myproject/comment_delete.html'
            form = CommentForm(instance=comment)
            context = {
                'form': form,
            }
            return render(request, template, context)
    except Exception as e:
        messages.warning(request, 'The comment could not be deleted. Error {}'.format(e))

models.py

class Comment(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField()
    published_date = models.DateField(auto_now_add=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.content

template.html

 <div class="class-one-box">
        <p>{{ comment.post.content }}</p>
        <p>Are you sure that you want to delete this Comment? If so, please confirm.</p>
        <form method="POST">
            {% csrf_token %}
            <button class="btn btn-danger" type="submit">Delete Comment</button>
        </form>
    </div>

1 个答案:

答案 0 :(得分:0)

是的,您需要通过上下文传递注释对象。所以尝试这样:

    if request.method == 'POST':
        comment.delete()
        messages.success(request, 'You have successfully deleted the Comment')
        return redirect('post_detail', pk=comment.post.pk)
    else:
        template = 'myproject/comment_delete.html'
        form = CommentForm(instance=comment)
        context = {
            'comment': comment,  # <-- Here
            'form': form,
        }
        return render(request, template, context)