Search code examples
djangovalidationsubclassingdjango-forms

Why does validation on a subclassed form break?


When i create CustomerForm() which is a subclass of EnhancedModelForm(), the changes (required=True) made when initializing the form with __init__() aren't taken in consideration by the default clean methods? Why is this?

class EnhancedModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(EnhancedModelForm, self).__init__(*args, **kwargs)
        test = self.errors

And the form

class CustomerForm(EnhancedModelForm):

    class Meta:
        model = Customer
        fields = ('salutation', 'first_name', 'last_name', 'phone_number', 'email_address')

    def __init__(self, *args, **kwargs):
        super(CustomerForm, self).__init__(*args, **kwargs)
        self.fields['phone_number'].required = True
        self.fields['email_address'].required = True

Solution

  • Instead of overriding the init() method, i now use the _post_clean() hook in django.forms.form.BaseForm()

    """
    An internal hook for performing additional cleaning after form cleaning
    is complete. Used for model validation in model forms.
    """
    

    This works great