You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django提交评论报错type object 'Post' has no attribute 'filter'如何解决

问题原因及修复方案

1. 核心报错原因

你触发AttributeError的根本原因是get_object()方法调用错误:
Django通用视图DetailView的get_object()方法不需要传入模型类参数,你在类中已经声明了model = Post,调用self.get_object()时会自动使用该模型查询。你传入了Post模型类作为参数,get_object()内部会尝试对传入的参数调用filter()方法,而模型类本身没有filter方法(只有模型的查询集QuerySet才有),因此触发报错。
修复方式:将post = self.get_object(Post)改为post = self.get_object()。

2. 其他代码问题

2.1 跳转逻辑错误

你的reverse调用存在两个问题:

  • 你在urls.py中为PostDetailView配置的路由名称是post-detail,不是post
  • 路由需要传入pk参数,而非content,且你写的Post.content是模型类的属性,不是当前帖子实例的属性
    修复方式:将redirect部分改为:
return redirect(reverse("post-detail", kwargs={
    'pk': post.pk
}))

2.2 回复赋值逻辑错误

你写的reply = comment_qs, reply=None是无效代码,实际是创建了一个元组赋值给了临时变量reply,没有关联到评论实例。你需要把回复对象赋值给form.instance的对应字段,假设你的Comment模型中存储父评论的字段名为reply,修复方式为:

if reply_id:
    comment_qs = Comment.objects.get(id=reply_id)
form.instance.reply = comment_qs

2.3 语法小错误

form.instance. user = request.user中instance和user之间多了一个空格,删除即可。

修复后完整post方法代码

def post(self, request, *args, **kwargs):
    form = CommentForm(request.POST)
    if form.is_valid():
        post = self.get_object()
        form.instance.user = request.user
        form.instance.post = post
        reply_id = request.POST.get('comment_id')
        comment_qs = None
        if reply_id:
            comment_qs = Comment.objects.get(id=reply_id)
        form.instance.reply = comment_qs
        form.save()
        form.save_m2m()

        return redirect(reverse("post-detail", kwargs={
            'pk': post.pk
        }))

内容的提问来源于stack exchange,提问作者Renaldo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:06:04