【问题标题】:Django wizard forms and dynamic formset creationDjango 向导表单和动态表单集创建
【发布时间】:2021-03-10 06:10:57
【问题描述】:

通常,在向导中,我们以静态方式声明表单或表单集,例如:

form_class=formset_factory(MyForm, min_num=1, extra=5)  # let's say this is step '4'

但是现在,如果我需要第 3 步的数据,知道如何为第 4 步的表单集定义 min_numextra 值怎么办?

我正在考虑在get_form() 方法中做这样的事情:

def get_form(self, step=None, data=None, files=None):
    form = super().get_form(step, data, files)

    # ....

    elif step == '4':
        step3_data = self.storage.get_step_data('3')

        # ... here I would parse step 3 data, to be able to define:
        computed_step_4_min_num = 5
        computed_step_4_extra = 10

        # And here I would need to call formset_factory(min_num=computed_step_4_min_num,
                                                        extra=computed_step_4_extra),
        # but how? This is obviously not the right place for this call.

虽然在get_form() 方法中编辑表单字段属性很容易,但我没有找到以动态方式定义正确数量的表单集的方法。

我阅读了文档,但我可能会错过它。感谢您的帮助。

【问题讨论】:

    标签: python django django-forms django-formwizard


    【解决方案1】:

    通过阅读documentationchecking the source code,我认为这是使用的最佳解决方案:

    def get_form(self, step=None, data=None, files=None):
        if step == '4':
            step3_data = self.storage.get_step_data('3')
            # do calculations
            computed_step_4_min_num = 5
            computed_step_4_extra = 10
            form = formset_factory(MyForm, min_num=computed_step_4_min_num, extra=computed_step_4_extra)
            self.form_list[step] = form
        return super().get_form(step, data, files)
    

    我将覆盖 self.form_list 以添加表单集工厂。但是您应该在启动 Wizard 实例时在视图中添加一个表单集:

    >> formset = formset_factory(MyForm, min_num=1, extra=1)
    >> MyWizardForm.as_view([Form1, Form2, Form3, formset], initial_dict=initial)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 2012-05-21
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2013-09-17
      • 2021-06-03
      相关资源
      最近更新 更多