Question

I want to provide my forms with nicer feedback using CSS. I'm already doing it but it's just a clean code matter. I have many ModelForms and I want all of them to behave in the same way, so I thought there should be a way to avoid duplicating code for validation.

I have created a new class which 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 lies in runing the parent validation since I don't know how to get the parent form... isn't there any way to get it from self?

Was it helpful?

Solution

You've misunderstood how inheritance works in Python. In a super method, you must always call the current class:

valid = super(ModelFormCSS, self).is_valid()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top