使用 class 扩展 Django ModelForm

Extend Django ModelForm with a class

我的 Django 项目中有多个模型表单,我想为所有这些表单添加三个字段。

但是当我编写一个简单的表单然后将其子类化时,出现错误。

class PersonForm(forms.Form):
    person_name = forms.CharField(
        label=u'Entregado por',
        max_length=64,
    )
    person_document_number = forms.CharField(
        label=u'Número de Documento',
        max_length=15,
    )
    person_document_type = forms.ChoiceField(
        label=u'Tipo de Documento',
        choices=BLANK_CHOICE_DASH + list(DOCUMENT_TYPE_CHOICES),
    )

class ContractForm(PersonForm, forms.ModelForm):
    class Meta:
        model = Contract

    def __init__(self, *args, **kwargs):
        super(ContractForm, self).__init__(*args, **kwargs)
        self.fields['person_name'].widget.attrs['class'] = 'js-person-name'

错误:

TypeError: Error when calling the metaclass bases
    metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

我试图定义一个PersonForm喜欢

class PersonForm:
    person_name = forms.CharField(
        label=u'Entregado por',
        max_length=64,
    )
    # ....

没有从forms.Form继承它,得到一个错误:

django.core.exceptions.FieldError: Unknown field(s) (person_document_type, person_document_number, person_name) specified for Contract

有什么漂亮的方法可以做到这一点(无需将这些字段复制到我所有的模型表单中)吗?

为什么不直接用 ModelForm 实现 PersonForm?

class PersonForm(forms.ModelForm):
    person_name = forms.CharField(
        label=u'Entregado por',
        max_length=64,
    )
    person_document_number = forms.CharField(
        label=u'Número de Documento',
        max_length=15,
    )
    person_document_type = forms.ChoiceField(
        label=u'Tipo de Documento',
        choices=BLANK_CHOICE_DASH + list(DOCUMENT_TYPE_CHOICES),
    )

class ContractForm(PersonForm):
    class Meta:
        model = Contract

    def __init__(self, *args, **kwargs):
        super(ContractForm, self).__init__(*args, **kwargs)
        self.fields['person_name'].widget.attrs['class'] = 'js-person-name'