Django: IntegrityError at /accounts/accounts/myprofile UNIQUE constraint failed: accounts_userprofile.user_id
Когда я пытаюсь обновить свой профиль пользователя, я получаю эту ошибку,
IntegrityError at /accounts/accounts/myprofile Сбой ограничения UNIQUE: accounts_userprofile.user_id
Я искал решения, но это не работает для меня.
модель:
class UserProfile(models.Model):
is_deligate = models.BooleanField(default=True)
is_candidate = models.BooleanField(default=False)
user = models.OneToOneField(CustomUser,
on_delete=models.CASCADE)
name = models.CharField(max_length=200)
stud_id = models.IntegerField(primary_key = True)
course_year_and_section = models.CharField(max_length=200)
def __str__(self):
return self.name
Форма:
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ['name','stud_id','course_year_and_section']
view:
def UserProf(request):
user = request.user
ls2 = UserProfile.objects.get(user_id=user.id)
form = UserProfileForm()
if request.method == 'POST':
form = UserProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
context = {'form':form,'ls2':ls2}
return render(request,"accounts/myprofile.html", context)
def UpdateUserProf(request):
form = UserProfileForm()
try:
prof = request.user
except UserProfile.DoesNotExist:
prof = UserProfile(user=request.user)
if request.method == 'POST':
form = UserProfileForm(request.POST,instance=prof)
if form.is_valid():
form.save()
return redirect("myprofile.html")
else:
form = UserProfileForm(instance=prof)
context = {'form':form}
return render(request,"accounts/myprofile.html", context)
У CustomUser может быть только один UserProfile, вот что означает OneToOneField, возможно, вы пытаетесь установить UserProfile для CustomUser с уже существующим. Проверьте, поможет ли это.
class UserProfile(models.Model):
is_deligate = models.BooleanField(default=True)
is_candidate = models.BooleanField(default=False)
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="profile")
name = models.CharField(max_length=200)
stud_id = models.IntegerField(primary_key = True)
course_year_and_section = models.CharField(max_length=200)
def __str__(self):
return self.name
def UserProf(request):
user = request.user
ls2 = UserProfile.objects.get(user_id=user.id)
form = UserProfileForm()
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=user.profile)
if form.is_valid():
profile = form.save()
context = {'form':form,'ls2':ls2}
return render(request,"accounts/myprofile.html", context)