如果用户在 formset 中填写的表单不完整,然后将其标记为删除,我的表单处理会非常糟糕。删除的表单会阻止 formset.cleaned_data 工作,因为它们没有验证,因此表单没有 clean_data 属性。如果我尝试遍历 formset.deleted_forms 并从 formset.forms 中删除表单,则 formset.cleaned_data 由于索引超出范围而崩溃。
我应该如何处理这些用户不想要的无效表单?
(这是我的错误,我从谷歌组复制了描述)
我不明白这个错误,因为查看 django 代码我可以读到这个:
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
err = self.errors
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete: <-------
if self._should_delete_form(form):
# This form is going to be deleted so any of its errors
# should not cause the entire formset to be invalid.
continue
if bool(self.errors[i]):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
此时,这是我避免错误的代码:
formFac = modelformset_factory(prm_model, extra = extra, can_delete = prm_can_delete )
if request.method == 'POST':
formSet = formFac( request.POST )
hi_ha_errors = False
if formSet.is_valid():
for form in formSet:
if form not in formSet.deleted_forms:
form.save()
for form in formSet.deleted_forms:
instance = form.instance
if instance.pk:
try:
instance.delete()
except Exception, e:
form._errors.setdefault(NON_FIELD_ERRORS, []).append(
'This row is referenced by others.' )
hi_ha_errors = True
if not hi_ha_errors:
return HttpResponseRedirect( prm_url_next )