首页 文章

如何在django 's custom formset'的clean方法中将“DELETE”参数重置为False

提问于
浏览
1

我用自定义清理方法制作了自定义formset . 它看起来像:

class MyFormsetBase(forms.models.BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        ....
        super(AdvOrderBidFormsetBase, self).__init__(*args, **kwargs)


    def clean(self):
        ....
        if error:
            raise forms.ValidationError('some validation error')

当我从formset中删除某个表单(带有错误的参数)并按下提交按钮(表单有DELETE字段值== True)时,我在我的clean方法中得到 error = True ,所以我得到ValidationError并返回到表单窗口 . 但是表单中的DELETE字段值不会重置 . 下次当我提交表单时,我会得到相同的ValidationError . 那么,我可以在自定义清理方法中以某种方式更改DELETE字段的值吗?

2 回答

  • 0

    即使这个问题很老,我最近也遇到了同样的问题 . 我可以通过使用form.data字典调整来重置DELETE字段 . 不是一个漂亮的解决方案,但它有效:

    class MyFormset(BaseModelFormSet):
        def clean(self):
            for form in self.deleted_forms:
                #iterating over only the forms marked for being delete
                if <YOUR_CONDITION>:
                    form.data = form.data.copy() # form.data is immutable unless we copy it
                    form.data.pop('{prefix}-DELETE'.format(form.prefix)) # Delete the correct 'DELETE' field from the POST data
                    form.cleaned_data.pop('DELETE') # Also remove the field from cleaned data as the formset checks this field for deletion
    
  • 1

    你在干净的方法中到底得到了什么?

    如果清除数据中仍包含“DELETE字段值”属性(或此短语的任何含义),则该属性将保持不变 .

    要删除它,请从已清理的数据中删除它 .

    这里报道了类似的问题,也许这有助于Clearing Django form fields on form validation error?

相关问题