SessionWizardView状态仅保存在最终表单上,done()未执行

wil*_*e01 7 django django-forms django-views django-formwizard

我有几个表单已添加到向导中,但表单状态仅在最后一步中保留,并且不执行done().

我已经根据django文档中的示例创建了以下内容,以尝试深入了解这一点.似乎最后一步是唯一一个在步骤之间移动时拯救状态的步骤.

class OneForm( Form ):
    field_one = forms.CharField(label='1', max_length=100)
    field_two = forms.CharField(label='2', max_length=100)
    field_three = forms.CharField(label='3', max_length=100)
class TwoForm( Form ):
    field_one = forms.CharField(label='4', max_length=100)
    field_two = forms.CharField(label='5', max_length=100)
    field_three = forms.CharField(label='6', max_length=100)

TEST_WIZARD_FORMS = [
    ("one", OneForm),
    ("two", TwoForm),
]
TEST_TEMPLATES = {
    'one': 'tour/one.html',
    'two': 'tour/two.html',
}
class TestWizardView( SessionWizardView ):
    form_list = TEST_WIZARD_FORMS
    def done(self, form_list, **kwargs):
        print('done executed')
        return reverse('home')
    def get_template_names(self):
        return [TEST_TEMPLATES[self.steps.current]]
Run Code Online (Sandbox Code Playgroud)

这对于模板(one.html和two.html都相同)

<html>
<body>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
    {{ wizard.form.management_form }}
    {{ wizard.form.non_field_errors }}
    {{ wizard.form.errors }}
    {% for form in wizard.form.forms %}
        {{ form }}
    {% endfor %}
{% else %}
    {{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"first step"</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</button>
{% endif %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.next }}">"next step"</button>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果我在步骤1中输入数据,请继续执行步骤2并输入数据,然后返回步骤1,第一步没有保存数据,也不显示任何表单错误.当我点击下一步返回步骤2时,第2步的数据仍然存在.故意在步骤1上放置无效数据表明我也没有验证表单,因为向导继续执行步骤2而不显示错误.

当我提交表单时,done()不会执行.如果只有最后一步实际上是成功的,那么这是有道理的,但是在步骤1中看到没有错误让我感到困惑.

除了最终表格之外,为什么不保留表格数据?为什么最后一步是实际验证表单数据的唯一步骤?为什么没有执行?

更新:似乎表单验证正在发生,我确实通过在post函数中打印相关信息看到它成功,但done()似乎仍未执行.

谢谢.

wil*_*e01 4

此处找到的文档中的步骤 1就是答案。它陈述如下。

用户访问向导的第一页,填写表单并提交。

这里的关键是“提交”。除非提交表单,否则不会保存表单验证或状态。使用 Wizard_goto_step 进行下一个/上一个/跳转不会提交表单,不会验证表单,并且不会将表单保存在会话/cookie 中(取决于您选择的选项)。

现在很明显,但我仍然认为这会误导表单向导的潜在最终用户。对我来说,在进入下一步时用实际提交替换 Wizard_goto_step 很容易,但是当用户在表单中输入一些数据,然后选择重新访问另一个步骤时,该步骤上的所有数据都会丢失。

感觉表单数据即使不完整也应该保存。我的目的是使用 storage.set_step_data() 函数手动保存此数据,因为无论如何,所有表单步骤都会在最终处理时重新验证。即使用户在某个步骤中填写了不正确的数据,他们仍然会被重定向到最后缺少数据的步骤。这感觉比在用户访问上一步时盲目擦除用户的数据更好。