Django:完整性错误唯一约束失败:user_profile.user_id [英] Django: Integrity error UNIQUE constraint failed: user_profile.user_id
问题描述
当我尝试编辑配置文件以向UserProfile模型添加信息时,出现了这个奇怪的错误:
When I am trying to edit a profile to add info to a UserProfile model, I am getting this strange error:
IntegrityError at /profiles/edit/
UNIQUE constraint failed: user_profile.user_id
出了什么问题在这里,
模型:
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(blank=True)
phone= models.CharField(max_length=10, blank=True)
address = models.CharField(max_length=1024)
age = models.PositiveIntegerField(blank=True,null=True)
gender = models.IntegerField(choices=GENDER_CHOICES, default=1)
表格:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('phone','age','gender','address','bio')
视图:
def edit_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST)
print request.POST
if form.is_valid():
new_profile = UserProfile(
user = request.user,
bio = request.POST['bio'],
address = request.POST['address'],
age = request.POST['age']
)
new_profile.save()
return HttpResponseRedirect(reverse('user_public_profile', args=(request.user.username,)))
return render(request,'users/edit_profile.html', {'form': form})
else:
form = UserProfileForm()
return render(request,'users/edit_profile.html',
{'form': form})
推荐答案
这并不奇怪。您已经有该用户的配置文件,因此添加另一个配置文件将打破唯一约束。您需要编辑现有的表单,而不是添加新的表单。
It's not strange. You already have a profile for that user, so adding another one breaks the unique constraint. You need to edit the existing one, not add a new one.
还请注意,保存时并没有使用已清理的表单数据。使用 form.cleaned_data ['bio']
等,甚至更好的方法是使用 form.save()
Also note that you're not using the cleaned form data when you save, which you should be. Either use form.cleaned_data['bio']
etc, or even better just do form.save()
which is the whole point of using a model form.
放在一起:
try:
profile = request.user.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile(user=request.user)
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return redirect...
else:
form = UserProfileForm(instance=profile)
return render...
这篇关于Django:完整性错误唯一约束失败:user_profile.user_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!