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})
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"),