重写Django窗体的元类

2024-09-29 01:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

ContactForm是我的应用程序中经常使用的一种形式。我已经在Guardian表中有了一个Foreign Keyof Contact模型

但是,当我不得不重用时,为下面的ContactForm字段再次编写整个表单有点复杂。因此将ContactForm分开以使其可重用

但有时ContactForm中仍然有少数字段是可选的,因此无法再次重用相同的ContactForm

class ContactForm(forms.ModelForm): 
    class Meta:
        model = Contact
        fields = ("address", "city", "district", "state", "country", 
                 "pincode", "phone1", "phone2", "is_emergency")

例如,从上面的ContactForm,我只想在GuardianForm中使用phone1phone2is_emergency标志。 是否仍然可以通过将ContactFormin继承到GuardianForm来重写Meta类,例如:

class GuardianForm(forms.ModelForm, ContactForm): #obviously this will not work
  first_name = forms.CharField(max_length=30, required=False, label = "First Name")
  last_name = forms.CharField(max_length=30, required=False, label = "Last Name")
  # Other Fields ...

  class Meta:
    model = Guardian
    fields = ('passport_number', 'pan_number', 'annual_income',
        'phone1', 'phone2', 'is_emergency',)  # Only 3 Fields of `ContactForm`

或者-有没有更好的标准方法来克服这个问题


Tags: namefieldsmodeliscontactformsmetaclass
1条回答
网友
1楼 · 发布于 2024-09-29 01:25:24

我不确定您想要实现什么,但以下是如何扩展Django Forms的元类:

class GuardianForm(ContactForm): 
    class Meta(ContactForm.Meta):
        fields = ("phone1", "phone2", "is_emergency")

相关问题 更多 >