Django FormWizard how to change the form_list dynamically

喜欢而已 提交于 2019-11-30 07:30:08

Instead of changing form list etc. in get_context_data(), I think more appropriate will be to implement get_form() method in your wizard view and return different form instance depending upon the step and previous data.

Something like this:

class UserServiceWizard(SessionWizardView):
    instance = None

    def get_form(self, step=None, data=None, files=None):
        if step is None:
            step = self.steps.current

        prev_data = self.get_cleaned_data_for_step(self.get_prev_step(
                                                    self.steps.current))
        if step == '1':
            service_name = str(prev_data['provider']).split('Service')[1]
            form_class = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ProviderForm')
            form = form_class(data)
        elif step == '3':
            service_name = str(prev_data['consummer']).split('Service')[1]
            form_class = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ConsummerForm')
            form = form_class(data)
        else:
            form = super(UserServiceWizard, self).get_form(step, data, files)

        return form

The trick here is do not change the length of form list (which you have done correctly), but just change form instance. Django has provided way to override get_form() method for this purpose. Django will honor this method and always use it to get the form instance for the method.

I'm not sure if it is the solution you are looking for, but if you modify form_list in process_step instead of in get_context_data it should work. You will have to change your code since process_step is executed after a form is submitted.

According to Django doc https://docs.djangoproject.com/en/1.5/ref/contrib/formtools/form-wizard/ process_step is the "Hook for modifying the wizard’s internal state", at least for self.kwargs vars (in fact your form_list is in self.kwargs["form_list"]) I have tested that all modifications in get_context_data are ignored so I think that self.form_list should behave in the same way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!