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

烈酒焚心 提交于 2020-07-10 03:43:05

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/60382260/django-db-utils-integrityerror-not-null-constraint-failed-users-profile-user-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!