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

Django博客评论举报功能提交时无法获取并保存对应评论ID

问题根源

  1. 现有举报表单未传递对应评论ID字段,后端无法获取对应评论标识,所以会抛出MultiValueDictKeyError
  2. 原有视图代码存在变量名拼写错误,FlagCommentForm、flagForm都是未定义变量,你实际实例化的表单对象是reportform
  3. Comment模型缺少关联Blog的外键字段,无法做跨博文举报的合法性校验

解决步骤

1. 调整表单类

排除需要后端赋值的字段,避免前端篡改关联数据

# forms.py
from django import forms
from .models import ReportComment

class CommentReportForm(forms.ModelForm):
    class Meta:
        model = ReportComment
        fields = ['text'] # 仅保留举报内容字段,关联字段全部由后端赋值

2. 补充评论模型的博文关联字段

# models.py 调整Comment类
class Comment(models.Model):
    commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE) # 新增关联博文的外键
    body = models.CharField(max_length=1000)

补充后执行makemigrations和migrate命令更新数据库结构。

3. 修改详情页模板

给每条评论的举报表单添加隐藏的评论ID字段,提交时同步传递当前评论的标识

<!-- blog_detail_page.html -->
{{post.title}}

{% for comment in post.comment_set.all %}
<p>{{comment.body}}</p>
<div class="container">
    <form method="post">
        {% csrf_token %}
        <!-- 新增隐藏字段传递当前评论ID -->
        <input type="hidden" name="comment_id" value="{{ comment.id }}">
        <table>
        {{ reportform }}
        </table>
        <button type="submit">提交举报</button>
    </form>
</div>
{% endfor %}

举报功能无需上传文件,可删除冗余的enctype="multipart/form-data"属性

4. 修正视图函数逻辑

# views.py
def blog_detail_page(request, blog_id):
    post = get_object_or_404(Blog, pk=blog_id)

    if request.method == 'POST':
        reportform = CommentReportForm(data=request.POST)
        if reportform.is_valid():
            form = reportform.save(commit=False)
            # 获取前端传递的评论ID
            comment_id = request.POST.get('comment_id')
            # 校验评论是否存在且属于当前博文,避免恶意提交
            comment = get_object_or_404(Comment, pk=comment_id, blog=post)
            # 赋值关联字段
            form.reported_comment = comment
            form.reported_by = request.user
            form.save()
            return redirect('home')

    else:
        reportform = CommentReportForm()

    context = {'reportform':reportform, 'post':post}
    return render(request, 'blog_detail_page.html', context)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:18:02