FormWizard and FileFields (Django 1.4)

点点圈 提交于 2019-11-30 15:52:02

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/10597021/formwizard-and-filefields-django-1-4

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