1

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

Michael
  • 8,357
  • 20
  • 58
  • 86

1 Answers1

2

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):
     ...
Community
  • 1
  • 1
seddonym
  • 16,304
  • 6
  • 66
  • 71