Override the function ModelForm is_valid

I want to provide my forms with more convenient feedback using CSS. I already do this, but this is just a clean question. I have a lot ModelForms, and I want them all to do the same, so I thought there should be a way to avoid duplicating the code for verification.

I created a new class that overrides ModelForm

class ModelFormCSS(forms.ModelForm):
    def is_valid(self):
        # run the parent validation first
        valid = super(-->ParentModelForm<--, self).is_valid()

        if not valid:
            for f_name in self.errors:
                classes = self.fields[f_name].widget.attrs.get('class', '')
                if not "errors" in classes:
                    classes += ' errors'
                    self.fields[f_name].widget.attrs['class'] = classes
            return valid

        # all good
        return True

My problem is doing the parent check, since I don’t know how to get the parent form ... is there no way to get it from self?

+4
source share
1 answer

, Python. super current:

valid = super(ModelFormCSS, self).is_valid()
+5

Source: https://habr.com/ru/post/1532800/


All Articles