gpt4 book ai didi

python - django.db.utils.IntegrityError : NOT NULL constraint failed: users_profile. user_id

转载 作者:行者123 更新时间:2023-12-03 08:48:29 25 4
gpt4 key购买 nike

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

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

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

NameError at /users/pii/

name 'self' is not defined

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

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'
]

最佳答案

您必须将 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用户添加配置文件。

关于python - django.db.utils.IntegrityError : NOT NULL constraint failed: users_profile. user_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60382260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com