djangodjango-formwizardformwizard

Django form wizard save and go to previous step


I have a working django formwizard which when I hit the previous button doesn't validate the current input.

I've tried variations on

<input name="wizard_goto_step" class="btn btn-primary btn-large" type="submit" value="prev"/>

and

<button class="btn btn-info btn-large"
        name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">
    {% trans "prev step" %}
</button>

but neither of these seems to do what I want to do.


Solution

  • If you want it to validate and save the data on the current form before stepping back to a previous form, you need to override the post() method in your subclass of SessionWizardView. The methods you're looking for are self.storage.set_step_data() and self.storage.set_step_files() to save the current form data.

    A rough example:

    def post(self, *args, **kwargs):                                                                                                                                                                                                                    
        go_to_step = self.request.POST.get('wizard_goto_step', None)  # get the step name                                                                                                                                               
        form = self.get_form(data=self.request.POST, files=self.request.FILES)                                                      
    
        current_index = self.get_step_index(self.steps.current)                                                                     
        goto_index = self.get_step_index(go_to_step)                                                                                
    
        if current_index > goto_index:    
            if form.is_valid():                                                                      
                self.storage.set_step_data(self.steps.current,                                                                          
                    self.process_step(form))                                                                                            
                self.storage.set_step_files(self.steps.current,                                                                         
                    self.process_step_files(form))                                                                                      
        else:                                                                                                                       
            return self.render(form)                                                                                                
        return super(NominateFormWizard, self).post(*args, **kwargs)