0

When I have a field which is hidden but specified in the modelform, it fails to pass validation. The below form fails to pass validation for the postcode field, even though I pass in the postcode data in the constructor. How do I attach data to it to pass validation correctly so that it can save?

eg

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
        }
Yunti
  • 6,761
  • 12
  • 61
  • 106

1 Answers1

0

Read this documentaion to understand why Initial is not suitable for your puposes.

Instead, override the 'is_valid' method. In 'is_valid', change the value of the hidden field AFTER the form is submitted. I got this solution here