django ModelForm中新增非必填項(not require)欄位方法
阿新 • • 發佈:2019-01-28
如一個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