在删除页面上显示注释内容

2024-04-18 05:57:13 发布

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

我无法在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>

Tags: pyselfformreturnmodelsrequestdefcomment
1条回答
网友
1楼 · 发布于 2024-04-18 05:57:13

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

    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)

相关问题 更多 >