django.db.utils.IntegrityError:NOT NULL约束失败:users_profile.user_id [英] django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id

查看:360
本文介绍了django.db.utils.IntegrityError:NOT NULL约束失败:users_profile.user_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个将吸收用户信息并将其存储的项目。我的问题是我不断遇到此NOT NULL约束,失败的原因是用户ID错误。我认为这是由于在尝试保存表单时使用空用户,但我不知道该如何解决。我尝试使用此行:

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

但它没有用,并给了我这个错误:



/用户/ pii /

中的


NameError

未定义名称'self'


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



模型。 py

  class Profile(models.Model):

user = models.OneToOneField (用户,on_delete = models.CASCADE)
图片= models.ImageField(默认='default.jpg',upload_to ='profile_pics')
性别= models.CharField(max_length = 1,选择= GENS ,默认='')
生日= models.DateField(默认='1900-01-01')
地址= AddressField(on_delete = False,blank = True,null = True)
race = models.CharField(max_length = 2,选择= RACES,默认='x')
种族= models.CharField(max_length = 1,选择=种族,默认='x')
收入=模型。CharField(max_length = 1,选择= INCBRACKET,默认='x')
教育=模型.CharField(max_length = 2,选择=教育,默认='x')
就业=模型。CharField(max_length = 1,选择=就业,默认='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)
(如果img.height> 300或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(请求,f'您的帐户已经创建!您现在可以登录')
return redirect('finalpii')
else:
form = PIIForm(request.POST)
return render(request,'users / pii.html',{'form':form})

forms.py

  PIIForm类( form.ModelForm):
生日= forms.DateField()
类元:
模型=个人资料
字段= [
'gender',
'生日,
地址,
种族,
ethnicit y'
]


解决方案

您必须进行编辑您的个人资料模型的用户字段为...

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

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



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



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


I am currently working on a project that would take in a users information and store it. My problem is I keep running into this NOT NULL constraint failed with the user id error. I believe this comes from having a null user when the form is trying to save, but don't know what I could do to fix it. I tried using this line:

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

but it didn't work and gave me this error:

NameError at /users/pii/

name 'self' is not defined

Any help or advice that would point me in the right direction would be greatly appreciated!

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

解决方案

You have to edit your user field of Profile model as...

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

null=True, Django will store empty values as NULL in the database. Default is False.

blank=True, form validation will allow entry of an empty value. Default is False.

Then run python manage.py makemigrations and python manage.py migrate commands and then you can add a profile with Null user.

这篇关于django.db.utils.IntegrityError:NOT NULL约束失败:users_profile.user_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆