ModelForm不会验证,因为在clean()中分配了缺少的字段

时间:2016-11-02 17:47:38

标签: django django-forms

我有一个ModelForm带有自定义保存方法,用url params(传递给表单)中的kwarg填充模型字段:

from app.models import MyModel
class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.fk_customer = kwargs.pop('customer')
        super(MyModelForm, self).__init__(*args, **kwargs)

    class Meta:
        model = MyModel
        fields = '__all__'

    def clean(self):
        cleaned_data = super(MyModelForm, self).clean()
        cleaned_data['fk_customer'] = self.fk_customer
        return cleaned_data

当我在视图中检查cleaned_data时,fk_customer存在且有效。但是is_valid()为false,ModelForm不会save()。如果我覆盖了一些内容并强行保存,则字段fk_customer会另存为None

发生了什么以及如何更改cleaned_data并仍然有效?

1 个答案:

答案 0 :(得分:1)

如果您没有在表单中显示customer字段,则应将其从表单类中排除,而不是使用__all__

然后,我会尝试使用表单的save方法而不是clean方法设置客户。以下是未经测试的:

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.customer = kwargs.pop('customer')
        super(MyModelForm, self).__init__(*args, **kwargs)

    class Meta:
        model = MyModel
        exclude = ('customer',)


    def save(self, commit=True)
        instance = super(MyModelForm, self).save(commit=False)
        instance.customer = self.customer
        if commit:
            instance.save()
            self.save_m2m()
        return instance