如何在ModelForm中创建某些字段= False?
如果我有:
class ThatForm(ModelForm):
class Meta:
widgets = {"text": Textarea(required=False)}
或者如果我有:
class ThatForm(ModelForm):
text = Textarea(required=False)
Django回归:
__init__() got an unexpected keyword argument 'required'
答案 0 :(得分:38)
以下评论。可能是的:
class ThatForm(ModelForm):
def __init__(self, *args, **kwargs):
# first call parent's constructor
super(ThatForm, self).__init__(*args, **kwargs)
# there's a `fields` property now
self.fields['desired_field_name'].required = False
答案 1 :(得分:21)
你应该将blank = True添加到相应的模型
如果模型字段为空= True,则表单字段上的required设置为False。否则,required = True。
另请参阅documentation for blank本身。
答案 2 :(得分:5)
当我们需要在许多字段上设置必填选项时,我们可以:
class ThatForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.Meta.required:
self.fields[field].required = True
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
'address',
'postcode',
'city',
'state',
'country',
'company',
'tax_id',
'website',
'service_notifications',
)
required = (
'email',
'first_name',
'last_name',
'address',
'postcode',
'city',
'country',
)
答案 3 :(得分:3)
以下可能适合
class ThatForm(ModelForm):
text = forms.CharField(required=True, widget=forms.Textarea)
答案 4 :(得分:-6)
你可以试试这个:
class ThatForm(ModelForm):
class Meta:
requireds =
{
'text':False,
}
必填项必须在Meta。
下