Django - 同时保存onetonone链接表单不起作用

时间:2016-12-23 17:53:19

标签: django django-forms

我有以下表格:

class UpdateProfile(forms.ModelForm):
    username = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name')

    def clean_email(self):
        username = self.cleaned_data.get('username')
        email = self.cleaned_data.get('email')

        if email and User.objects.filter(email=email).exclude(username=username).count():
            raise forms.ValidationError('This email address is already in use. Please supply a different email address.')
        return email

class UserDetailForm (forms.ModelForm):
    linked_user = forms.CharField (required = True)
    linked_password = forms.CharField (required = True, widget = forms.PasswordInput())
    connections = forms.IntegerField (required = True)

    class Meta:
        model = User_detail
        fields = ('linked_user','linked_password','connections')

如果两者都有效,我正试图同时保存它们:

    if request.method == 'POST':
        form = UpdateProfile(request.POST, instance=request.user)
        linked_form = UserDetailForm(request.POST, instance=request.user)
        if all((form.is_valid(),linked_form.is_valid())):
            user = form.save()
            linked = linked_form.save(commit=False)
            linked.user = user
            linked.save()
            msg = "Profile Updated"
        else:
            return error(request)

这是User_detail模型:

class User_detail (models.Model):
    user = models.OneToOneField (
        User,
        on_delete = models.CASCADE
        )
    linked_user = models.CharField (
        verbose_name = 'LinkedIn Username',
        max_length = 50,
    )
    linked_password  = models.CharField (
        max_length = 50,                                
        verbose_name = 'LinkedIn Password',
    )
    connections = models.IntegerField (
        verbose_name = 'Connections per day',
        default = 24,
    )
    def __unicode__(self):
        return u'%s' % (self.user.first_name + ' ' + self.user.last_name)

第一种形式正在保存,第二种形式没有,我不明白我缺少什么

非常感谢。

1 个答案:

答案 0 :(得分:1)

问题出在linked_form = UserDetailForm(request.POST, instance=request.user)request.user不是模型User_detail的实例。

发生的事情是,django试图在模型中找到实例而没有找到任何实例。您需要提供有效的User_detail实例,以便django可以更新该实例。

参考:save() method