[Django]-Django: Integrity error UNIQUE constraint failed: user_profile.user_id

30๐Ÿ‘

โœ…

Itโ€™s not strange. You already have a profile for that user, so adding another one breaks the unique constraint. You need to edit the existing one, not add a new one.

Also note that youโ€™re not using the cleaned form data when you save, which you should be. Either use form.cleaned_data['bio'] etc, or even better just do form.save() which is the whole point of using a model form.

Putting that together:

try:
    profile = request.user.userprofile
except UserProfile.DoesNotExist:
    profile = UserProfile(user=request.user)

if request.method == 'POST':
    form = UserProfileForm(request.POST, instance=profile)
    if form.is_valid():
        form.save()
        return redirect...
else:
    form = UserProfileForm(instance=profile)
return render...
๐Ÿ‘คDaniel Roseman

9๐Ÿ‘

I was getting the same error multiple times and I was really disheartened but finally came over the solution.

Convert:

user = models.OneToOneField(User)

to

user = models.ForeignKey(User)

This should solve the issue.

2๐Ÿ‘

Consider the case: If the same user makes the post request again on URL โ€˜profile/editโ€™ then your code will try to create the new UserProfile using the same user instance, but since this is a one to one field and you have already created one profile using that user hence it will throw integrity error.

So you should check first if the profile associated with that user already exists or not, then if it didnโ€™t exist then create it.

๐Ÿ‘คlocalhost_3000

0๐Ÿ‘

add (instance = request.user) in UserProfileForm(request.POST)

๐Ÿ‘ค 0536

0๐Ÿ‘

I accidentally got this error because I forgot to specify update_fields in my call to save. I had:

modified_instance.save(video_attr)

When I should have had:

modified_instance.save(update_fields=[video_attr])

The truthy string was being interpreted as the positional force_update parameter, which obviously causes problems if the record already exists.

๐Ÿ‘คCarcigenicate

-2๐Ÿ‘

Yes you are making a OneToOne relation between User and UserProfile models thatโ€™s why you are facing integrity error,
for fixing this you can change it to ForeignKey
Like :

class UserProfile(models.Model):

user = models.ForeignKey(User,on_delete=models.CASCADE)
bio = models.TextField(blank=True)
...
...
๐Ÿ‘คvipin yadav

Leave a comment