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

Django2添加笔记报错:IntegrityError,NOT NULL约束失败:notes_note.created

解决Django新增笔记时的IntegrityError问题

你遇到的IntegrityError at /notes/add NOT NULL constraint failed: notes_note.created错误,核心原因是你的Note模型中created字段被设置为非空约束,但在保存笔记对象时没有给这个字段赋值,导致数据库拒绝写入。下面是两种针对性的解决方案:

方案1:让Django自动填充创建时间(推荐)

如果created字段是用来记录笔记的创建时间,最省心的方式是在模型里设置auto_now_add=True,这样Django会在对象第一次保存到数据库时自动将该字段设置为当前时间,不需要手动处理:

# models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

class Note(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)  # 示例字段,根据你的实际模型调整
    content = models.TextField()  # 示例字段
    created = models.DateTimeField(auto_now_add=True)  # 关键:自动添加创建时间

    def __str__(self):
        return self.title

修改模型后,记得运行迁移命令更新数据库:

python manage.py makemigrations
python manage.py migrate

方案2:在视图中手动赋值创建时间

如果你需要自定义created字段的取值(比如不是当前时间),可以在视图中手动给字段赋值后再保存:

# views.py
from django.shortcuts import render, redirect
from django.utils import timezone  # 记得导入timezone
from .forms import NoteForm

def note_add(request): 
    if request.method == 'POST': 
        form = NoteForm(request.POST) 
        if form.is_valid(): 
            new_form = form.save(commit=False) 
            new_form.user = request.user 
            new_form.created = timezone.now()  # 手动设置创建时间
            new_form.save() 
            return redirect('/notes') 
    else: 
        form = NoteForm() 
    context={ 
        "form":form, 
    } 
    return render(request, 'add.html', context )

为什么原来的代码会报错?

你使用form.save(commit=False)时,只是生成了Note对象但没有写入数据库,此时你只给user字段赋了值,却遗漏了created字段。而数据库中created字段默认是NOT NULL(非空)的,所以当你调用new_form.save()时,数据库会抛出约束错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:27:30