[Django]-Django form how to create a simple mixin

1👍

I’ve solved with inheritance:

class myBaseFormMixin(forms.ModelForm):  

then the special form :

class SpecialManForm(myBaseFormMixin)

2👍

You should change your SpecialManForm so that it uses your mixin first.

class SpecialManForm(myBaseFormMixin, forms.ModelForm)
    def __init__(self, *args, **kwargs):
        ....

When python is looking for the clean method, it will first check the SpecialManForm class, where it isn’t implemented. It will then go through the inheritance heirarchy, which means checking ModelForm first (as you currently have it). It is implemented there, so it will use the code from ModelForm, rather than from your mixin, and execute that.

Changing the order in the class definition means that it will check your mixin before the ModelForm class for the clean method, and use the method that you have implemented.

It checks (your version) in the following order SpecialManForm -> ModelForm -> myBaseFormMixin, and that explains why it worked when you added the method to the SpecialManForm.

Leave a comment