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

实现博客评论功能时提交表单报错:(1048, "Column 'comment_post_id' cannot be null")

评论提交报错(1048, "Column 'comment_post_id' cannot be null")的解决办法
  • 核心错误:外键字段名不匹配
    你的blogComment模型中,关联BlogPost的外键字段是comment_post,但在views.py的提交逻辑里,错误地给不存在的user_comment.blog赋值,导致comment_post字段未被填充,触发数据库非空约束报错。

    修正views.py中的赋值代码:

    # 原错误代码
    user_comment.blog = blog
    # 改为正确字段名
    user_comment.comment_post = blog
    
  • 修复博客不存在时的异常
    当通过slug找不到对应博客时,blog会被设为None,后续执行comments = blog.comments.filter(...)会抛出AttributeError。需要增加判断避免报错:

    comments = []
    if blog:
        comments = blog.comments.filter(comment_status=True)
    
  • 修正模板上下文的重复键问题
    你在render函数中重复使用comments作为键名,后者会覆盖前者,导致模板无法获取刚提交的评论。调整键名避免冲突:

    return render(request, 'view-blog.html', {
        'blog': blog, 
        'slug': slug, 
        'new_comment': user_comment,
        'comments': comments, 
        'comment_form': comment_form
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:10:54