无法在评论删除页面上显示帖子标题

时间:2019-05-17 11:59:32

标签: python django

我的社区站点上有帖子对象,评论可以与它们相关。我有一个额外的评论删除模板,我想在该页面的面包屑上显示帖子标题,但是由于某种原因,我将帖子对象设置在views.py上下文中后,我无法立即显示标题,任何提示都是有帮助的。我在这里做错什么了?

views.py

def comment_delete(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    post = get_object_or_404(Post, pk=pk)
    if request.user == comment.author:
        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 = 'app/Post/post_comment_delete.html'
            form = CommentForm(instance=comment)
            context = {
                'comment': comment,
                'form': form,
                'post': post
            }
            return render(request, template, context)
    else:
        messages.warning(request, 'Comment could not be deleted.')
        return redirect('post_detail', pk=comment.post.pk)

template.html:

<a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }} </a>

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(max_length=500)
    published_date = models.DateField(auto_now_add=True, null=True)

3 个答案:

答案 0 :(得分:1)

您似乎对帖子和评论使用了相同的主键。

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

您确定这是正确的吗?如果您以pk = 1调用此函数,它将获得注释并发布ID为1的帖子,也许没有发布该ID的帖子?

编辑: 如果您的评论中引用了帖子,请按以下方式访问它:

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

答案 1 :(得分:1)

删除评论实例后,您将无法访问已删除实例的字段,如果您需要访问与删除评论实例相关的“发布” pk,那么您可能会在删除评论之前先“发布”实例:

<div tabindex="0"></div>
<div tabindex="0"></div>
<div tabindex="0"></div>

答案 2 :(得分:0)

从以上答案中得出的解决方案:

def comment_delete(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    post = comment.post
    if request.user == comment.author:
        if request.method == 'POST':
            post = Post.objects.get(pk=comment.post.pk)
            comment.delete()
            messages.success(request, 'You have successfully deleted the comment.')
            return redirect('post_detail', pk=post.pk)
        else:
            template = 'app/Post/post_comment_delete.html'
            form = CommentForm(instance=comment)
            context = {
                'comment': comment,
                'post': post,
                'form': form

            }
            return render(request, template, context)
    else:
        messages.warning(request, 'Comment could not be deleted.')
        return redirect('post_detail', pk=comment.post.pk)

非常感谢您的帮助!