如何处理formset中无效的已删除表单

时间:2012-06-17 19:22:59

标签: django django-forms

如果用户填写formset中的表单不完整,然后将其标记为删除,我的表单处理可怕地死亡。删除的表单会阻止formset.cleaned_data工作,因为它们不验证,因此表单没有cleaning_data属性。如果我尝试迭代formset.deleted_forms并从formset.forms中删除表单,那么由于索引超出范围,formset.cleaned_data会崩溃。

我应该如何处理用户不想要的这些无效表​​单?

(这是我的错误,我复制了google groups的说明)

我不明白错误,因为查看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 )     

1 个答案:

答案 0 :(得分:0)

我解决此问题的方法是重写Formset / ModelFormset中使用的Form / ModelForm的full_clean()方法

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()

如果选中了表单删除框,则会清除错误列表。.表单将显示无错误。但是,如果用户取消选中删除框并重新提交,则表单将正常显示错误。