NOT NULL 约束失败:/jobs/add/ 处的jobs_job.created_by_id IntegrityError
Posted
技术标签:
【中文标题】NOT NULL 约束失败:/jobs/add/ 处的jobs_job.created_by_id IntegrityError【英文标题】:NOT NULL constraint failed: jobs_job.created_by_id IntegrityError at /jobs/add/ 【发布时间】:2021-06-27 00:57:48 【问题描述】:我正在尝试使用户能够添加工作,并且在填写表单后我收到了该错误。这是我的代码:
models.py
from django.db import models
from django.contrib.auth.models import User
class Job(models.Model):
title = models.CharField(max_length=255)
short_description = models.TextField()
long_description = models.TextField(blank=True, null=True)
created_by = models.ForeignKey(User, related_name='jobs', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
changed_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import AddJobForm
from .models import Job
def job_detail(request, job_id):
job = Job.objects.get(pk=job_id)
return render(request, 'jobs/job_detail.html', 'job': job)
@login_required
def add_job(request):
if request.method == 'POST':
form = AddJobForm(request.POST)
if form.is_valid():
job = form.save(commit=True)
job.created_by = request.user
job.save()
return redirect('dashboard')
else:
form = AddJobForm()
return render(request, 'jobs/add_job.html', 'form': form)
forms.py
from django import forms
from .models import Job
class AddJobForm(forms.ModelForm):
class Meta:
model = Job
fields = ['title','short_description','long_description']
我需要做什么来解决这个错误?我尝试从views.py
中删除commit=True
,我尝试删除sqlite3 并再次进行迁移。
【问题讨论】:
【参考方案1】:您正在尝试保存没有created_by
值的对象(因此出现错误消息),然后为该字段分配一个值并再次保存。你应该改变
job = form.save(commit=True)
到
job = form.save(commit=False)
所以第一个.save
实际上不会尝试向数据库提交任何内容。它仅用于构造Job
实例,以便您可以补全任何缺失值并使用job.save()
实际保存它。
请注意,如果您省略 commit=
参数,则假定为 True
。
【讨论】:
以上是关于NOT NULL 约束失败:/jobs/add/ 处的jobs_job.created_by_id IntegrityError的主要内容,如果未能解决你的问题,请参考以下文章