7

如果用户在 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 )     
4

1 回答 1

0

我解决这个问题的full_clean()方法是覆盖我在 Formset/ModelFormset 中使用的 Form/ModelForm的方法

class MyModelForm(ModelForm):

    def full_clean(self, *args, **kwargs):
        super(MyModelForm, self).full_clean(*args, **kwargs)
        if hasattr(self, 'cleaned_data') and self.cleaned_data.get('DELETE', False):
            self._errors = ErrorDict()

如果选中表单删除框,则会清除错误列表。表单将显示为没有错误。但是如果用户取消选中删除框并重新提交,那么表单将照常显示错误。

于 2018-10-18T22:26:07.640 回答