Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormWizard and FileFields (Django 1.4)

My FormWizard (Django 1.4) allows the user to step back and forth until he completes the wizard. The wizard keeps all the values the user filled in and displays them in case the user goes back to a step he already completed.

This works fine i.e. for CharField but does not work for FileFields. In case the user submits a file in a step containing a FileField and later goes back to this step, he has to upload a file again.

Is there a way the user won't have to re-upload the file?

Please note that the form data have not yet been saved to the database.

like image 769
mbaechtold Avatar asked Nov 04 '22 00:11

mbaechtold


1 Answers

I recently run into the same problem, and could solve it by subclassing Django's SessionWizardView (in my case NamedUrlSessionWizardView), and overriding the get_form method.

Basicly I do the the following:

  • Get the files that are already stored for the step.
  • Iterate over the current submitted files.
  • If a submitted file is None, ignore it, else overwrite the already stored value.

Here is the code:

from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView

class MyWizardView(NamedUrlSessionWizardView):

    def get_form(self, step=None, data=None, files=None):
        if step:
            step_files = self.storage.get_step_files(step)
        else:
            step_files = self.storage.current_step_files

        if step_files and files:
            for key, value in step_files.items():
                if files.has_key(key) and files[key] is not None:
                    step_files[key] = files[key]
        elif files:
            step_files = files

        return super(MyWizardView, self).get_form(step, data, step_files)
like image 187
beachmachine Avatar answered Dec 04 '22 15:12

beachmachine