带隐藏字段的Django Model表单不会通过验证

时间:2017-10-26 13:12:40

标签: django django-forms

当我有一个隐藏但在模型中指定的字段时,它无法通过验证。即使我在构造函数中传递了邮政编码数据,下面的表单也无法通过邮政编码字段的验证。如何将数据附加到它以正确传递验证以便它可以保存?

例如

class SupplyAddressForm(forms.ModelForm):
    full_address = forms.ChoiceField()

    def __init__(self, postcode, *args, **kwargs):
        super().__init__(*args, **kwargs)
        raw_addresses_data = get_full_address(postcode)
        addresses = raw_addresses_data['data']['addresses']
        ...........
        self.fields['postcode'].initial = postcode



    def save(self, commit=False):
        address = super().save(commit=False)
        cd = self.cleaned_data
        full_address = cd['full_address']
        full_address = json.loads(full_address)
        ......
        return address

    class Meta:
        model = Address
        fields = [
            'supply_months',
            'supply_years',
            'postcode',
            'residential_status',
        ]

        widgets = {
             'postcode': forms.HiddenInput
        }

1 个答案:

答案 0 :(得分:0)

阅读此documentaion以了解为什么Initial不适合您的目的。

相反,覆盖'is_valid'方法。 在'is_valid'中,在提交表单后更改隐藏字段的值。我得到了这个解决方案here