2015-02-24 51 views
1

我在我的Django項目中有多個模型表單,並且想要爲它們添加三個字段。用類擴展Django ModelForm

但是,當我寫一個簡單的表單,然後子類化它,我得到一個錯誤。

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 

有沒有美麗的方式來做到這一點(沒有將這些字段複製到我的模型表單中)?

+0

http://code.activestate.com/recipes/204197-solving-the-metaclass-conflict/檢查 – cdvv7788 2015-02-24 19:56:48

回答

2

爲什麼不直接在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' 
+0

謝謝!現在看起來很明顯:) – vero4ka 2015-02-24 21:43:42