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

Django未渲染for循环内HTML代码,评论无法显示求助

修复建议:你的图片画廊评论功能的几个关键问题

我帮你梳理下导致评论不显示的核心问题,一步步来修复:


1. 模板与视图的变量名不匹配(最直接的原因)

你的模板里循环用的是{% for comment in comments %},但在views.py的上下文里,你把评论列表存在了单数的comment变量里:

context = {'comment_form': comment_form, 'image': image,'comment': comment, ...}

模板找不到comments这个变量,自然不会渲染循环内容。把上下文里的键改成复数的comments:

context = {
    'comment_form': comment_form, 
    'image': image,
    'comments': comment,  # 这里改成复数comments,和模板变量对应
    'new_comment': new_comment
}

2. 评论关联对象错误(导致评论无法正确关联图片)

你的代码里有个致命的未定义变量错误:

new_comment.post = post  # 这里的post变量根本没定义!

你要关联的是当前的image(也就是Picture模型的实例),所以应该改成:

new_comment.image = image  # 这里要和你的Comment模型里的外键字段名一致,比如如果外键是picture,就写new_comment.picture = image

另外要注意你的Comment模型关联设置:如果外键字段的related_name设为comments,那查询图片的评论应该用:

comment = image.comments.filter(active=True)  # 对应related_name

如果没设置related_name,就用Django默认的命名:

comment = image.comment_set.filter(active=True)

3. 补充用户关联+清理冗余代码

你的代码里没给评论关联当前登录用户,还有重复初始化的冗余代码,建议优化成这样:

@login_required
def add_comment(request, image_id):
    template_name = 'add_comment.html'
    image = get_object_or_404(Picture, id=image_id)
    comments = image.comments.filter(active=True)  # 用正确的查询方式
    new_comment = None

    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.user = request.user  # 关联当前登录用户
            new_comment.image = image  # 关联到当前图片
            new_comment.save()
    else:
        comment_form = CommentForm()

    context = {
        'comment_form': comment_form,
        'image': image,
        'comments': comments,
        'new_comment': new_comment
    }
    return render(request, template_name, context)

4. 修复模板的HTML转义问题

你的模板代码里有<和>这类转义字符,要改成正常的尖括号才能正确渲染:

{% for comment in comments %}
<div class="comments" style="padding: 10px;">
    <p class="font-weight-bold">
        <h4>Comment by</h4> 
        {{ comment.user }} 
        <span class="text-muted font-weight-normal">
            {{ comment.created_on }}
        </span>
    </p>
    {{ comment.body | linebreaks }}
</div>
{% endfor %}

做完这些修改后,先确认评论能正确保存到数据库(关联对应用户和图片),再测试页面应该就能正常显示评论列表了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:07:33