在工做中常常會遇到ModelForm中添加非必填項(not require)字段。html
如一個form中,想要address這個字段是一個非必填項。相關代碼以下segmentfault
class My_Form(ModelForm): class Meta: model = My_Class fields = ('first_name', 'last_name' , 'address')
第一種解決辦法post
class My_Form(ModelForm): address = forms.CharField(required=False) class Meta: model = My_Class fields = ('first_name', 'last_name' , 'address')
第二種解決辦法:ui
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
原文網址:http://www.chenxm.cc/post/577...code