【发布时间】:2019-09-07 08:15:38
【问题描述】:
Django 决定在我提交表单时抛出一个错误。该表单是一个模型表单集,我完全没有更改默认设置,只需单击提交按钮。 Django 抱怨唯一的空表单需要有一个值,当我将其更改为 required = False 时:
forms.CharField(max_length = 40, required = False)
它停止抱怨。这是我的表格:
class RateForm(ModelForm):
costcode = forms.CharField(max_length = 40, required = False)
class Meta:
model = Rate
fields = ['costcode', 'rate', 'UOM', ]
class BaseRateFormSet(BaseModelFormSet):
def clean(self):
''' No custom cleaning at this point.'''
cd = super(BaseRateFormSet, self).clean()
为了查看发生了什么,我编写了自定义清理,当我在其后添加 assert False 时,发现 cd 为 None。
观点:
rate_formset = RateFormSet(request.POST if any(request.POST) else None,
prefix = user.short_name,
form_kwargs = the_form_kwargs,
**user_form_kwargs)
实际上,字段 costcode 应该是必需的,但 Django 应该意识到用户不希望提交任何额外的表单,因此它不会产生错误。如何让 Django 不在空表单上抛出错误?
【问题讨论】:
标签: django django-forms django-views