Skip to content Skip to sidebar Skip to footer

Django Formwizard How To Change The Form_list Dynamically

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_list is remaining unchanged. here is w

Solution 1:

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:

classUserServiceWizard(SessionWizardView):
    instance = Nonedefget_form(self, step=None, data=None, files=None):
        if step isNone:
            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.

Solution 2:

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.

Post a Comment for "Django Formwizard How To Change The Form_list Dynamically"