Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda