实现博客评论功能时提交表单报错:(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
相关产品推荐
相关产品推荐

