Django: Integrity error UNIQUE constraint failed: user_profile.user_id

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.


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...

Tags:

Django