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.
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()
.