当我试图更新一个现有的用户配置文件时,我会得到这个错误,
IntegrityError at /accounts/accounts/myprofile唯一约束失败: accounts_userprofile.user_id
我一直在寻找解决办法,但这对我不起作用。
模型:
类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表格:
类UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ['name','stud_id','course_year_and_section']意见:
def UserProf(请求):
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(请求):
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)发布于 2022-10-24 09:17:50
CustomUser只能有一个UserProfile,这就是OneToOneField的意思,也许您试图用现有的UserProfile为CustomUser设置一个UserProfile。看看这是否有帮助。
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)https://stackoverflow.com/questions/74178545
复制相似问题