Django form wizard save and go to previous step

十年热恋 提交于 2019-12-03 22:12:53

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) 

One (arguably elegant) way would be to use a different POST variable than wizard_goto_step, and then override WizardView.get_next_step():

def get_next_step(self, step=None):
    return self.request.POST.get('wizard_next_step',
            super().get_next_step(step))

Then, use name="wizard_next_step" on the previous-step button/link. This approach both has the advantage that the old behavior remains available should you need it, and that you're not re-implementing WizardView.post().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!