如何使 django formset 中的所有表单都需要?我试图验证cleaned_data
覆盖 formset 的 clean() 方法中所有字段的存在,但它只是默默地失败,没有显示任何错误。
谢谢!
源代码:
class BaseScheduleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseScheduleForm, self).__init__(*args, **kwargs)
self.fields['day'].widget = forms.HiddenInput()
self.fields['user'].widget = forms.HiddenInput()
class Meta:
model = Schedule
def clean_end_time(self):
start_time = self.cleaned_data.get('start_time')
end_time = self.cleaned_data['end_time']
if start_time and end_time:
if end_time <= start_time:
raise forms.ValidationError("End time must be later that start time.")
return end_time
class BaseScheduleFormset(forms.models.BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(BaseScheduleFormset, self).__init__(*args, **kwargs)
for number, weekday in enumerate(WEEKDAYS):
self.forms[number].day_name = weekday[1]
def clean(self):
raise forms.ValidationError('You must specify schedule for the whole week')
ScheduleFormset = forms.models.modelformset_factory(Schedule, extra=7, max_num=7,
form=BaseScheduleForm, formset=BaseScheduleFormset)
一天有7张表格,必须全部填写才有效。在上面的示例中,我只是尝试在 clean 中引发错误。is_valid()
变为 False,但没有显示错误。