【问题标题】:Django FormWizards: How to painlessly pass user-entered data between forms?Django FormWizards:如何在表单之间轻松传递用户输入的数据?
【发布时间】:2023-03-20 03:12:01
【问题描述】:

我在 Django 1.4.3 中使用 FormWizard 功能。

我已经成功创建了一个 4 步表单。在表单的前 3 个步骤中,它正确地从用户那里获取信息,对其进行验证等。在第 4 步中,它现在只显示一个“确认”按钮。没有其他的。当你在第 4 步点击“确认”时,在 done() 函数中使用它做一些有用的事情。到目前为止一切正常。

但是,我想在第 4 步(确认步骤)中向用户显示他们在之前的步骤中输入的数据以供他们查看。我试图找出最轻松的方法来实现这一点。到目前为止,我正在上下文中创建一个名为 formList 的条目,其中包含已完成的表单列表。

class my4StepWizard(SessionWizardView):

    def get_template_names(self):
        return [myWizardTemplates[self.steps.current]]

    def get_context_data(self, form, **kwargs):
        context = super(my4StepWizard, self).get_context_data(form=form, **kwargs)
        formList = [self.get_form_list()[i[0]] for i in myWizardForms[:self.steps.step0]]

        context.update(
            {
                'formList': formList,
            }
        )
        return context        


    def done(self, form_list, **kwargs):
        # Do something here.
        return HttpResponseRedirect('/doneWizard')

Form #1 有一个名为 myField 的输入字段。 所以在我的第 4 步模板中,我想做 {{ formList.1.clean_myField }}。但是,当我这样做时,我收到以下错误:

异常值:
“my4StepWizard”对象没有属性“cleaned_data”

看来我放入 formList 的表单是无限的。所以它们不包含用户的数据。有没有可以用来获取数据本身的修复程序?我真的很想像上面那样使用上下文来传递数据。

【问题讨论】:

    标签: django django-forms django-templates


    【解决方案1】:

    试试这个:

    def get_context_data(self, form, **kwargs):
        previous_data = {}
        current_step = self.steps.current # 0 for first form, 1 for the second form..
    
        if current_step == '3': # assuming no step is skipped, this will be the last form
            for count in range(3):
                previous_data[unicode(count)] = self.get_cleaned_data_for_step(unicode(count))
    
        context = super(my4StepWizard, self).get_context_data(form=form, **kwargs)
        context.update({'previous_cleaned_data':previous_data})
        return context
    

    previous_data 是一个字典,它的键是向导的步骤(0 索引)。每个键对应的项目是cleaned_data,用于步骤中的表单,与键相同。

    【讨论】:

    • 这个解决方案存在三个问题: 问题 #11) range(4) 应该是 range(3) 问题 #2) self.steps.current 不是整数。它是一种形式的名称。问题 #3) 即使我修复了 #1 和 #2,previous_data 看起来像这样:{0: None, 1: None, 2:None}。那里没有数据。
    • 您对这些问题是正确的。我在睡觉时间之后发布了答案。我已经编辑了帖子以检查“3”而不是 3。我在生产代码中有类似的东西,它可以工作。如果您没有提供不会作为正确表单步骤传递的 int 或字符串,例如“0”、“1”而不是“确认”或“第一页”,我看不出有任何理由为什么你应该得到 None
    • 感谢您回复并修复 Tundebabzy。然而,根本问题是 self.get_cleaned_data_for_step(unicode(count)) 总是返回 None。
    • 抓挠我的头,但是当您解决了问题时,请务必在此处发布。我很想知道你是如何解决这个问题的
    • 好的,如果我找到答案,我会在这里发布。仅供参考“cleaned_data_for_step”应该是“get_cleaned_data_for_step”。
    猜你喜欢
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多