django.db.utils.IntegrityError:NOT NULL 约束失败:users_profile.user_id

Posted

技术标签:

【中文标题】django.db.utils.IntegrityError:NOT NULL 约束失败:users_profile.user_id【英文标题】:django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id 【发布时间】:2020-06-08 10:58:54 【问题描述】:

我目前正在从事一个项目,该项目将接收用户信息并将其存储。我的问题是我一直遇到这个 NOT NULL 约束失败并出现用户 ID 错误。我相信这来自于在表单试图保存时有一个空用户,但不知道我能做些什么来修复它。我尝试使用这一行:

form.user = Profile.objects.get(user=self.request.user)

但它不起作用并给了我这个错误:

/users/pii/ 处的名称错误

名称'self'未定义

任何能指引我正确方向的帮助或建议将不胜感激!

models.py

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    gender = models.CharField(max_length = 1, choices = GENS, default = '')
    birthday = models.DateField(default = '1900-01-01')
    address = AddressField(on_delete=False, blank=True, null=True)
    race = models.CharField(max_length = 2, choices = RACES, default = 'x')
    ethnicity = models.CharField(max_length = 1, choices = ETHNICITIES, default = 'x')
    income = models.CharField(max_length = 1, choices = INCBRACKET, default = 'x')
    education = models.CharField(max_length = 2, choices = EDUCATION, default = 'x')
    employment = models.CharField(max_length = 1, choices = EMPLOYMENT, default = 'x')

    def __str__(self):
        return f'self.user.username Profile'
    def save(self, *args, **kawrgs):
        super().save(*args, **kawrgs)
        img = Image.open(self.image.path)
        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

views.py

def PII(request):
    if request.method == 'POST':
        form = PIIForm(request.POST,)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('finalpii')
    else:
        form = PIIForm(request.POST)
    return render(request, 'users/pii.html', 'form':form)

forms.py

class PIIForm(forms.ModelForm):
    birthday = forms.DateField()
    class Meta:
        model = Profile
        fields = [
        'gender',
        'birthday',
        'address',
        'race',
        'ethnicity'
        ]

【问题讨论】:

你不需要self - request 是视图的参数。也无需查询Profile.objects.get( - request.user 是您所需要的 ***.com/questions/17312831/… 这能回答你的问题吗? Add data to ModelForm object before saving 【参考方案1】:

您必须将Profile 模型的user 字段编辑为...

user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)

null=True,Django 会将空值作为 NULL 存储在数据库中。默认为 False。

blank=True,表单验证将允许输入空值。默认为 False。

然后运行python manage.py makemigrationspython manage.py migrate 命令,然后您可以添加带有Null 用户的配置文件。

【讨论】:

以上是关于django.db.utils.IntegrityError:NOT NULL 约束失败:users_profile.user_id的主要内容,如果未能解决你的问题,请参考以下文章