【问题标题】:IntegrityError at /notes/add NOT NULL constraint failed: notes_note.created/notes/add NOT NULL 约束处​​的 IntegrityError 失败:notes_note.created
【发布时间】:2020-08-01 21:15:16
【问题描述】:

当我在 django2 中添加函数时遇到问题,无法添加新帖子而这段代码

/notes/add 处的完整性错误 NOT NULL 约束失败:notes_note.created

这些观点

    def note_add(request):

    # form = NoteForm()
    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.save()
            return redirect('/notes')
    else:

        form = NoteForm()

    context={
        "form":form,
    }
    return render(request, 'add.html', context )

【问题讨论】:

  • IntegrityError at /notes/add NOT NULL 约束失败:notes_note.created
  • idownvotedbecau.se/imageofcode 没有dv,但请复制问题中的代码,请勿发布代码图像。
  • @memeal:可以分享一下模型吗?

标签: python html css django web


【解决方案1】:

您没有为 Note 模型中的 created 字段设置默认值。结果,没有填写任何值,因此出现错误:您可以将auto_now_add=… parameter [Django-doc] 设置为True 以自动将其设置为创建对象时的时间戳:

class Note(models.Model):
    # …
    created = models.DateTimeField(auto_now_add=True)

通常情况下最好更改包裹在表单中的.instance,并让表单.save() 成为模型。如果您(稍后)向Note 模型添加多对多关系,这将特别有用,因为表单以更透明的方式处理此逻辑:

def note_add(request):
    if request.method == 'POST':
        form = NoteForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('/notes')
    else:
        form = NoteForm()
    context={
        'form': form,
    }
    return render(request, 'add.html', context)

【讨论】:

  • 非常感谢您解决问题
猜你喜欢
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多