Michael
Michael

Reputation: 8778

form mixin for a modelform?

Why does the following not give a final model form with 3 fields?

The two extra fields are not available. If I move them directly into the model form, it works but I wanted to declare these fields in a separate form because I plan on reusing them in several forms. Is there a way to do that?

class FormA(forms.Form):
    extra_field_1 = forms.CharField(required=False)
    extra_field_2 = forms.CharField(required=False)

class ModelFormA(FormA, forms.ModelForm):
    class Meta:
        model = ModelA
        fields = ['email']

Thanks Mike

Upvotes: 1

Views: 827

Answers (1)

seddonym
seddonym

Reputation: 17239

It's more complicated than you'd think to achieve this using that approach, because of the way in which Django uses metaclasses. (More details in this answer.)

I'd try overriding the constructor - (and note that the mixin extends from object now):

class MyFormMixin(object):
    def __init__(self, *args, **kwargs):
        super(MyFormMixin, self).__init__(*args, **kwargs)
        self.fields['extra_field_1'] = forms.CharField(required=False)
        self.fields['extra_field_2'] = forms.CharField(required=False)

class ModelFormA(MyFormMixin, forms.ModelForm):
     ...

Upvotes: 2

Related Questions