Django IntegrityError:NOT NULL约束失败accounts_solution.puzzle_id求助
问题根源分析与解决方案
你遇到的IntegrityError NOT NULL constraint failed: accounts_solution.puzzle_id错误,核心原因是你的评论表单关联错了模型!
为什么会出现这个错误?
看你的AddCommentForm代码,Meta类里把model设成了Solution,但这个表单明明是用来创建Comment实例的啊!
当你在视图里调用form.save(commit=False)时,生成的对象其实是Solution类型,而不是Comment。虽然你手动给这个对象赋值了user和solution,但它本质上还是一个需要puzzle关联的Solution模型实例——你没给它设置puzzle字段,自然就触发了非空约束的错误。
你打印的那些内容看起来没问题,是因为你确实拿到了合法的Solution对象,但你操作的根本不是Comment!
修正步骤
只需要把AddCommentForm的关联模型改成Comment即可,修正后的表单代码如下:
class AddCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddCommentForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['placeholder'] = 'Title' self.fields['content'].widget.attrs['placeholder'] = 'Content' content = forms.CharField( widget = forms.Textarea(attrs={"rows": 6,}), ) class Meta: model = Comment # 这里改成Comment! fields = ['title', 'content']
后续验证
修改后,form.save(commit=False)会生成一个Comment实例,你给它赋值user和solution后保存,就不会再要求puzzle_id了——因为Comment模型里根本没有这个字段,它只需要关联已有的Solution即可,而Solution本身已经和Puzzle绑定了。
你的视图逻辑本身是没问题的,只要表单模型改对,这个错误就会消失。
内容的提问来源于stack exchange,提问作者ohjuny
相关产品推荐
相关产品推荐

