将文件绑定到表单Django向导

时间:2013-02-06 16:12:41

标签: django forms wizard

所以我是来自django-merlin的unsuccessful at hooking up the Session-based wizard,但我正在尝试使用django源中包含的向导。但是,当尝试使用ImageField上传文件时,似乎文件request.FILES未绑定到表单,因为在尝试上载文件后,我收到“此字段是必需的”错误。这就是我所拥有的:

forms.py:

class StepOneForm(forms.Form):
    year = forms.ChoiceField(choices=YEAR_CHOICES)
    ...

class StepTwoForm(forms.Form):
    main_image = forms.ImageField()
    ...

class CreateWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
    def done(self, form_list, **kwargs):
        d['main_image'] = request.FILES['main_image']
        db = Thing(**d)
        db.save()
        return render(request, 'wizard-done.html', {
            'form_data': [form.cleaned_data for form in form_list],
        })

在上面的CreateWizard中,我尝试将main_image方法保存在done方法中discussed in this stackoverflow question,但我没有成功。


更新:

添加enctype=multipart/form-data允许我绑定文件,但现在我收到一个新错误:

global name 'request' is not defined

即使请求上下文处理器在我的TEMPLATE_CONTEXT_PROCESSORS中。在链接的stackoverflow帖子中定义done方法也不起作用:

class CreateWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
    def done(self, request, form_list):

会产生TypeError: done expects 3 arguments, 2 given

1 个答案:

答案 0 :(得分:2)

您需要self.request

return render(self.request, 'wizard-done.html', {
        'form_data': [form.cleaned_data for form in form_list],  })