Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
How to update one-to-one relationship model?

I have a model that has a one-to-one relationship with the User. I created a form that creates the model, but if that form is submitted again it gives "UNIQUE constraint failed". How can i make it so the data gets updated instead of it trying to create a new one?

models.py

class Userprofile (models.Model):
    user = models.OneToOneField(User, related_name='profile', primary_key=True,)
    address = models.CharField(max_length=100)
    zip = models.CharField(max_length=100)

forms.py

class Profile(forms.ModelForm):
    class Meta:
        model = Userprofile
        fields = ['address', 'zip']

views.py

def changeprofile(request):
    form = Profile(request.POST or None, request.FILES or None)
    if form.is_valid():
        profile = form.save(commit=False)
        profile.user = request.user
        profile.save()
        return render(request, 'myaccount.html', {"Profile":form})
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you got this error UNIQUE constraint failed because you are trying to create a new user again which already existed in the Userprofile table OneToOne Field will always check whether the user is unique in the table Userprofile.

So if you want to update the profile. Your view should be like this:

views.py

from django.shortcuts import get_object_or_404

def changeprofile(request):
    profile_instance = get_object_or_404(Userprofile, user=request.user)
    form = Profile(request.POST or None, request.FILES or None, instance=profile_instance)
    if form.is_valid():
        profile = form.save(commit=False)
        profile.save()
        return render(request, 'myaccount.html', {"Profile":form})

urls.py

url(r'^update-profile/$', views.changeprofile, name="changeprofile"),
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!