Django FormWizard how to change the form_list dynamically

后端 未结 2 1714
醉酒成梦
醉酒成梦 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.

提交回复
热议问题