Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Integrity error UNIQUE constraint failed: user_profile.user_id

Tags:

django

When I am trying to edit a profile to add info to a UserProfile model, I am getting this strange error:

IntegrityError at /profiles/edit/
UNIQUE constraint failed: user_profile.user_id

What is wrong here,

model:

class UserProfile(models.Model):

    user = models.OneToOneField(User)
    bio = models.TextField(blank=True)
    phone= models.CharField(max_length=10, blank=True)
    address = models.CharField(max_length=1024)
    age = models.PositiveIntegerField(blank=True,null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)

form:

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('phone','age','gender','address','bio')

view:

def edit_profile(request):

    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        print request.POST
        if form.is_valid():

            new_profile = UserProfile(
                            user = request.user,
                            bio = request.POST['bio'],
                            address = request.POST['address'],
                            age = request.POST['age']
                            )

            new_profile.save()

            return HttpResponseRedirect(reverse('user_public_profile', args=(request.user.username,)))
        return render(request,'users/edit_profile.html', {'form': form})

    else:
        form = UserProfileForm()
        return render(request,'users/edit_profile.html',
                          {'form': form})
like image 392
yayu Avatar asked Oct 30 '14 11:10

yayu


2 Answers

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...
like image 125
Daniel Roseman Avatar answered Nov 12 '22 09:11

Daniel Roseman


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.

like image 8
Shubham Gupta - TCH Avatar answered Nov 12 '22 10:11

Shubham Gupta - TCH