嵌套Django Forms:“ManagementForm数据丢失或已被篡改”

2024-06-09 13:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我环顾四周,似乎没有人有同样的问题,我必须造成这个看似常见的错误。我正在html中呈现一些表单,如下所示:

<form method="post" action="">
{{ tags_formset.management_form }}

<!-- code displaying this formset -->
...
<!-- -->

    <form method="post" action="">
        {{ add_all_form.management_form }}
        {{ add_all_form.addTagsToAll }}
        <input type="submit" value="Add To Displayed Applicants" />
    </form>

    <form method="post" action="">
        {{ remove_all_form.management_form }}
        {{ remove_all_form.removeTagsFromAll }}
        <input type="submit" value="Remove From Displayed Applicants" />
    </form>
    <input type="submit" value="Save Changes" />
</form>

当我没有两个内部表单时,表单集将正确显示,提交按钮可用于提交表单。当我添加第二个表单时,出现了两个问题:

-提交按钮停止工作(尽管在选择了表单集的一个字段时按回车键,仍然会提交表单

-add_all_表单的提交工作正常(不是问题,但对下一点感兴趣…)

-remove_all_表单无法通过“ManagementForm数据丢失或已被篡改”验证错误工作。

下面是创建表单的views.py代码:

    TagsFormSet = formset_factory(TagsForm, formset=TagFormSet, extra=applicantQuery.count())
    if request.method == 'POST':
        tags_formset = TagsFormSet(request.POST, request.FILES, prefix='tags', applicants=applicantQuery)
        add_all_form = TagAddAllForm(request.POST, request.FILES, prefix='addForm', applicants=applicantQuery)
        remove_all_form = TagRemoveAllForm(request.POST, request.FILES, prefix='removeForm', applicants=applicantQuery)
        redirect = False
        if tags_formset.is_valid():
            for tagForm in tags_formset.forms:
                if 'tags' in tagForm.cleaned_data:
                    tagForm.saveTags()
                if 'removeTags' in tagForm.cleaned_data:
                    tagForm.deleteTags()                        
            redirect = True
        if add_all_form.is_valid():
            if 'addTagsToAll' in add_all_form.cleaned_data:
                add_all_form.saveTagsToAll()
            redirect = True
        if remove_all_form.is_valid():
            if 'removeTagsFromAll' in remove_all_form.cleaned_data:
                remove_all_form.deleteTagsFromAll()
            redirect = True
        if redirect:
            return http.HttpResponseRedirect('')
    else:
        initForms = []
        tags_formset = TagsFormSet(prefix='tags', applicants=applicantQuery)
        add_all_form = TagAddAllForm(prefix='addForm', applicants=applicantQuery)
        remove_all_form = TagRemoveAllForm(prefix='removeForm', applicants=applicantQuery)

我真的搞不清出了什么问题。我不知道为什么添加所有表单在删除所有表单不起作用时起作用,因为我基本上复制并粘贴了所有涉及的内容(如果需要,我可以从Forms.py文件中发布代码,但我不认为有问题…)

请帮忙!


Tags: informadd表单prefixifrequesttags