Django-按评论删除后重定向

时间:2019-07-01 02:55:46

标签: python django

我有一个代码可以删除帖子中的评论。

def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.delete()

    return redirect('Post-detail', pk=post.pk)

它删除注释,但引发错误,name 'post' is not defined 我在views.py中具有与上面相同的post.pk相同的功能,效果很好...

@login_required
def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            #comment.author.photo = object.author.profile.image.url
            comment.save()
            return redirect('Post-detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form})

评论模型

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=20)
    text = models.TextField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text

有人可以向我解释一下,问题出在哪里? 它不带post.pk而是带有comment.pk吗?

1 个答案:

答案 0 :(得分:2)

您可以像这样从评论对象中选择pk

comment = get_object_or_404(Comment, pk=pk)
....
return redirect('Post-detail', pk=comment.post_id)