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

Eth*_*Jay 2 python django django-models django-forms

我目前正在开发一个项目,该项目将接收用户信息并存储它。我的问题是我一直遇到这个 NOT NULL 约束因用户 ID 错误而失败。我相信这是因为当表单尝试保存时有一个空用户,但不知道我可以做什么来修复它。我尝试使用这一行:

form.user = Profile.objects.get(user=self.request.user)
Run Code Online (Sandbox Code Playgroud)

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

/users/pii/ 处的名称错误

名称“self”未定义

任何可以为我指明正确方向的帮助或建议将不胜感激!

模型.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)
Run Code Online (Sandbox Code Playgroud)

视图.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})
Run Code Online (Sandbox Code Playgroud)

表格.py

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

MK *_*tel 5

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

user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

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

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

然后运行python manage.py makemigrations命令python manage.py migrate,然后您可以使用用户添加配置文件Null