Search code examples
djangoformwizard

Can a step be repeated in Django 1.6 form wizard?


Can a step be repeated in the Django form wizard? I'd like to repeat a step an indefinite number of times depending on the needs of the user.


Solution

  • The documentation for the form wizard has directions on how to make conditional steps. I used that along with a function factory to make a few hundred conditional steps, so essentially the user can repeat the last step as many times as they want.

    from django.contrib.formtools.wizard.views import SessionWizardView
    from myapp.forms import BasicInformation, MoreInformation
    
    
    def function_factory(cond_step):
    
        def info(wizard):
            cleaned_data = wizard.get_cleaned_data_for_step(str(cond_step)) or {}
            return cleaned_data.get("add_another_step", False)
    
        return info
    
    
    def make_condition_stuff(extra, cond_step):
        cond_funcs = {}
        cond_dict = {}
        form_lst = [
            BasicInformation,
            MoreInformation,
        ]
    
        for x in range(extra):
            key1 = "info{0}".format(x)
            cond_funcs[key1] = function_factory(cond_step)
            cond_dict[str(cond_step+1)] = cond_funcs[key1]
            form_lst.append(MoreInformation)
    
        return cond_funcs, cond_dict, form_lst
    
    
    last_step_before_extras = 1
    extra_steps = 300
    
    cond_funcs, cond_dict, form_list = make_condition_stuff(
        extra_steps,
        last_step_before_extras
    )
    
    
    class InfoWizard(SessionWizardView):
        form_list = form_list
        condition_dict = cond_dict
        ...