Django Form Wizard, how to reset/clear wizard?
-
26-06-2021 - |
Question
I have created a Django Form Wizard which works fine. However, after finishing the wizard and starting it again, it loads the data generated during its previous use. Instead I would like it to clear the previous wizard state and start over once it was finished successful. I have tried modifying the done method of the wizard, but it doesn't do the trick:
def done(self, form_list, **kwargs):
self.instance_dict = {}
self.storage.reset()
return HttpResponseRedirect('/foo/')
What do I have to change to make the wizard work the way I need it? My wizard extends the NamedUrlSessionWizardView
class.
Solution
I am not 100% sure if this is true, but I think the following worked:
I was saving instances of forms in my wizard like this:
self.instance_dict['foo'] = foo
but for some reason
self.instance_dict = {}
didn't clear that data. Instead I moved to saving the objects in extra data:
self.storage.extra_data = {'foo' : foo}
Which I then retrieve inside the def get_form_instance(self, step)
method of the wizard, for example like this:
def get_form_instance(self, step):
...
if self.steps.current == 'foo' and self.storage.extra_data.has_key('foo'):
return Bar.objects.filter(foo=self.storage.extra_data['foo'])
...
That data apparently got cleared successfully with the above mentioned done method. However, in the end I dropped the whole form-wizard thing due to more complications and just went with a one-step form.
OTHER TIPS
It's really easy to reset the storage of a Form Wizard. I usually do that after the data processing is finished:
def done(self, form_list, form_dict, **kwargs):
#do stuff with your form data
self.instance_dict = None
self.storage.reset()
return redirect(reverse_lazy('somewhere'))
Or reset the Wizard after the redirect from another view
del request.session['wizard_name']