【发布时间】:2014-10-30 11:23:04
【问题描述】:
当我尝试编辑配置文件以将信息添加到 UserProfile 模型时,我收到了这个奇怪的错误:
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})
【问题讨论】:
-
不是针对您的问题,但是当我不小心更改
ModelForm.save(commit=False)上的对象字段时遇到了同样的错误,或者至少它与我处理commit的方式有关。跨度>
标签: django