在用于编辑用户个人资料的django视图功能中,我在保存时看到id == None。表单和模型都没有明确引用UserProfile.id和User.id. UserProfile模型具有此典型行
class UserProfile(models.Model):
...
user = models.OneToOneField(User)
因此表格结束:
class Meta:
"""Provide an association between ModelForm and model."""
model = UserProfile
fields = ('address', 'postal_code', 'city', 'country', 'date_of_birth')
所有看起来都很直接,但在保存时,我发现完整性违规。数据库是一个测试数据库,有两个用户,我非常确定,通过详尽检查这两个条目,id字段是可以的。
def edit_profile(request):
"""Edit/create a user's profile."""
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
print(form.cleaned_data) # looks reasonable
profile = form.save(commit=False)
# profile.user = User.objects.get(id=request.user.id)
profile.user = request.user
print('id=', profile.id) # Why is this None?
# On save, we'll get Integrity error,
# UNIQUE constraint failed: kernel_userprofile.user_id
profile.save() # Integrity error
print('form saved')
return HttpResponseRedirect(reverse('kernel/profile'))
# TODO(jeff@purple.com): Debug only, at most.
print(form.errors)
else:
my_profile = UserProfile.objects.get(user=request.user)
form = ProfileForm(instance=my_profile)
return render(request, 'kernel/profilemod.html', {'form': form})
任何指针?
答案 0 :(得分:1)
profile.id
字段在profile.save()
方法中设置,然后profile
首次创建。
IntegrityError
是因为您尝试创建新的UserProfile
而不是保存旧的instance
。要解决此问题,您应将ProfileForm
参数传递给form = ProfileForm(request.POST,
instance=UserProfile.objects.get(user=request.user))
构造函数:
first()
编辑:如果您想在单个视图中修改和创建个人资料,请使用get()
代替def edit_profile(request):
profile = UserProfile.objects.filter(user=request.user).first()
if request.method == 'POST':
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
...
else:
form = ProfileForm(instance=profile)
阅读个人资料以进行修改:
{{1}}