表单验证/保存时UserProfile id ==无

时间:2015-01-15 08:32:00

标签: django django-forms django-views

在用于编辑用户个人资料的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})

任何指针?

1 个答案:

答案 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}}