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

Django添加Comment评论时出现非空约束报错求排查

问题原因

你触发非空约束报错的核心原因是外键字段名赋值不匹配:

  • 在Comment模型中,你定义的关联Certification的外键字段名为certificate
  • 但在视图certificatePage的保存逻辑中,你错误地给不存在的certi字段赋值,导致必填的certificate字段没有值,触发报错。

修复方案

  1. 修正视图中的字段赋值代码,找到如下代码段:
if form.is_valid():
    comment = form.save(commit=False)
    comment.certi = certi
    comment.save()

将comment.certi = certi修改为:

comment.certificate = certi

修改完成后即可解决当前的非空约束报错。

  1. 额外语法修正(非当前报错直接原因,建议修改)
    你提供的forms.py存在缩进错误,Meta类和__init__方法都属于CommentForm类的内容,需要缩进一层,修正后的代码如下:
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = '__all__' 
        exclude = ['certificate']
    
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update(
            {'class': 'form-control form-control-sm',})
        
        self.fields['body'].widget.attrs.update(
            {'class': 'form-control form-control-sm',})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:09:03