Django FormWizard how to change the form_list dynamically

后端 未结 2 1715
醉酒成梦
醉酒成梦 2020-12-30 14:44

I\'m able to dynamically call one form related to the data I chose from the step ealier.

But when I\'m in the done method I can see the my form_li

相关标签:
2条回答
  • 2020-12-30 15:26

    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.

    0 讨论(0)
  • 2020-12-30 15:26

    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.

    0 讨论(0)
提交回复
热议问题