""Save" method throws duplicate key value violates unique constraint

2,399 views
Skip to first unread message

Menaga Gopal

unread,
Apr 6, 2020, 7:45:55 PM4/6/20
to Django users




Hello,

I have 2 tables:

1) CustomUser table
     - Id 
     - Email
     - Name

2) UserProperties table
     - id
     - user (foreign key with one to one relationship)
     - address
     - payment_details


  -  have mapped one to one relationship for the field "user" in the UserProperties table as below.

user = models.OneToOneField(CustomUser, on_delete= models.CASCADE)

  - Below is my view.py. When I try to save the user profile, the data is saved for the very first time (ie., when there is no such record for the user in the Userproperties table. However when I try to update the same user profile I get Integrity error.

IntegrityError at /users/profile
duplicate key value violates unique constraint "users_userproperties_user_id_key"
DETAIL:  Key (user_id)=(4) already exists.


@login_required
def profile(request):
    if request.method == 'POST':
        profile_form = UserProfileForm(request.POST)
        if profile_form.is_valid():
            profile = profile_form.save(commit=False
            profile.user = request.user                                
            profile.save()
            messages.success(request, f'Your Profile has been updated.')
            return redirect('profile')
    else:
        profile_form = UserProfileForm()
    return render(request,'profile.html',{'profile_form': profile_form})

I am new to django, please help me solve this issue.

Thanks in advance.


VenkataSivaRamiReddy

unread,
Apr 6, 2020, 10:10:00 PM4/6/20
to django...@googlegroups.com
Use in place of one to one model field place foreign key field

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/580f2a57-eda2-49f9-b42c-b9885ffd82f8%40googlegroups.com.

Menaga Gopal

unread,
Apr 7, 2020, 9:24:16 AM4/7/20
to Django users
Thank you for the response.

I was able to fix it by setting "user" field as the primary key in UserProperties model.

Below is the updated version of the user field in UserProperties model. Just added "primary_key=True" to fix the duplicate key value issue.

class UserProperties(models.Model):
    user = models.OneToOneField(CustomUser, on_delete= models.CASCADE,primary_key=True)

On Tuesday, April 7, 2020 at 4:10:00 AM UTC+2, VenkataSivaRamiReddy wrote:
Use in place of one to one model field place foreign key field

To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages