Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda