在工作中经常会遇到 在django中ModelForm添加非必填项(not require)字段。
如一个form中,想要address这个字段是一个非必填项。相关代码如下
class My_Form(ModelForm): class Meta: model = My_Class fields = ('first_name', 'last_name' , 'address')
第一种解决办法
class My_Form(ModelForm): address = forms.CharField(required=False) class Meta: model = My_Class fields = ('first_name', 'last_name' , 'address')
第二种解决办法:
class My_Form(forms.ModelForm): class Meta: model = My_Class fields = ('first_name', 'last_name' , 'address') def __init__(self, *args, **kwargs): super(My_Form, self).__init__(*args, **kwargs) self.fields['address'].required = False