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

Django博客评论回复系统报错:Cannot resolve keyword 'slug' into field

问题解决方案

错误根源

你在继承自DetailView(模型为Post)的ShowSingleNews视图中,错误重写了get_queryset方法,返回了Comment模型的查询集。当Django通过URL中的slug参数获取单篇文章时,会使用这个错误的查询集去匹配,但Comment模型并没有slug字段,因此触发FieldError。

修复步骤

1. 恢复正确的视图查询集

删除错误的get_queryset定义,或者让它返回Post模型的查询集:

class ShowSingleNews(DetailView):
    model = Post
    template_name = 'blog/single_news.html'
    context_object_name = 'post'
    raise_exception = True

    form = CommentForm

    # 移除错误的get_queryset方法,或者改为返回Post查询集:
    # def get_queryset(self):
    #     return Post.objects.all()

    # 其他方法保持不变...

2. 在上下文数据中添加顶级评论查询集

要获取当前文章的无回复评论(即顶级评论,非回复内容),在get_context_data方法中添加筛选逻辑,过滤出comm_to_repl为空的评论:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # 优化:直接使用已获取的文章对象,避免重复查询
    context['title'] = self.object.title
    context['form'] = self.form
    # 添加顶级评论查询集:关联当前文章且无父评论
    context['top_level_comments'] = Comment.objects.filter(
        post_of_comment=self.object,
        comm_to_repl__isnull=True
    ).order_by('-created')
    # 浏览量更新逻辑保留
    self.object.views = F('views') + 1
    self.object.save()
    self.object.refresh_from_db()

    return context

3. 修改模板使用新的评论数据集

将模板中遍历post.comments.all的部分,替换为遍历top_level_comments,确保只展示顶级评论,回复内容仍通过comment.replies.all嵌套展示:

<ul class="commentlist">
{% if not top_level_comments %} </br>
    <h5>No comments yet...</h5>
{% else %}
{% for comment in top_level_comments %}
    <li>
        <article class="comment">
            <!-- 原有评论展示代码保持不变 -->
            <header class="comment-author">
                <img src="{{ user.image.url }}" alt="">
            </header>
            <section class="comment-details">
                <div class="author-name">
                    <h5><a href="#">{{ comment.user_created_comment.username }}</a></h5>
                    <p>{{ comment.created }}</p>
                </div>
                <div class="comment-body">
                    <p>{{ comment.comment_content }} </p>
                </div>
                <div class="reply">
                    <!-- 回复表单代码保持不变 -->
                </div>
            </section>
            <!-- 回复内容遍历逻辑保留 -->
            {% if comment.replies.all %}
                {% for reply in comment.replies.all %}
                    <ul class="children">
                        <!-- 回复展示代码保持不变 -->
                    </ul>
                {% endfor %}
            {% endif %}
        </article>
    </li>
{% endfor %}
{% endif %}
</ul>

额外优化建议

  • 移除Post模型中的comment外键:Comment已通过post_of_comment关联到Post,且Post已有comments反向关联(由related_name='comments'定义),该字段属于冗余关联,会导致逻辑混乱。
  • 修复评论回复的空值处理:在post方法中,判断commrepl是否为空,避免空字符串转整数报错:
commrepl = request.POST.get("commentID")
if commrepl:
    form.instance.comm_to_repl_id = int(commrepl)
else:
    form.instance.comm_to_repl_id = None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:55:29