Meta类用于动态构造表单定义 - 因此,在您创建ModelForm实例时,不在排除中的字段已添加为新对象的属性.
执行此操作的常规方法是为每个可能的排除列表提供多个类定义.但是如果你希望表单本身是动态的,你必须动态创建一个类定义.就像是:
def get_form(exclude_list): class MyForm(ModelForm): class Meta: model = Passenger exclude = exclude_list return MyForm form_class = get_form(('field1', 'field2')) form = form_class()
更新:我刚刚重访这篇文章,并认为我会发布一个更惯用的方式来处理动态类:
def PassengerForm(exclude_list, *args, **kwargs): class MyPassengerForm(ModelForm): class Meta: model = Passenger exclude = exclude_list def __init__(self): super(MyPassengerForm, self).__init__(*args, **kwargs) return MyPassengerForm() form = PassengerForm(('field1', 'field2'))
其他方式:
class PassengerInfoForm(ModelForm): def __init__(self, *args, **kwargs): exclude_list=kwargs.pop('exclude_list', '') super(PassengerInfoForm, self).__init__(*args, **kwargs) for field in exclude_list: del self.fields[field] class Meta: model = Passenger form = PassengerInfoForm(exclude_list=['field1', 'field2'])