在 FormWizard 中使用 FileField (Django 1.3)

发布于 2025-01-06 10:22:12 字数 932 浏览 2 评论 0原文

我正在尝试使用 Django 1.3 FormWizard 上传文件,分两个步骤: 1. 仅文件字段 2. 如果文件已正确上传且有效(自定义验证后),请提供名称和描述。

在文档之后,我写道:

class CreateCheckWizard(FormWizard):
    def done(self, request, form_list):
        return HttpResponseRedirect('/my_checks/')
    def get_template(self, step):
        return ['create_check_%s.html' % step, 'create_check_1.html']

class CreateCheckForm1(forms.Form):
    my_file = forms.FileField()

class CreateCheckForm2(forms.Form):
    title = forms.CharField(max_length=255)

我将 multipart/form-data 添加到模板中的 FORM 标记中:

但是,即使我上传文件,也会收到错误“此字段是必填字段”。

我猜想该表单是在创建时省略了 request.FILES 字段的。 我们如何更改该行为以在 FormWizard 中成功上传文件?

编辑:查看 Django 源代码,它确实使用 form(request.POST) 而不是 form(request.POST, request.FILES) 创建表单,就像它应该的那样来处理文件。 有什么办法可以在不改变源代码的情况下上传文件吗?

I am trying to use a Django 1.3 FormWizard to upload a file with 2 steps:
1. Only the FileField
2. If the file was correctly uploaded and valid (after custom validation), offer to give it a name and description.

Following the documentation, I wrote:

class CreateCheckWizard(FormWizard):
    def done(self, request, form_list):
        return HttpResponseRedirect('/my_checks/')
    def get_template(self, step):
        return ['create_check_%s.html' % step, 'create_check_1.html']

class CreateCheckForm1(forms.Form):
    my_file = forms.FileField()

class CreateCheckForm2(forms.Form):
    title = forms.CharField(max_length=255)

I added the multipart/form-data to the FORM tag in the template:
<form enctype="multipart/form-data" action="." method="post">

However, even if I upload a file, I get the error "This field is required."

I guess the form is created omitting the request.FILES field.
How can we change that behaviour to successfully upload files in the FormWizard?

Edit: Looking at Django source code, it indeed create the forms using form(request.POST) instead of form(request.POST, request.FILES) like it should be to handle files.
Any way to upload files without changing the source code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一影成城 2025-01-13 10:22:12

这在 Django 1.3 表单向导中是不可能的。来自 Django 表单向导文档:

重要限制:由于向导使用 HTML 隐藏字段在页面之间存储数据,因此您不能包含除最后一个之外的任何形式的 FileField

这可以通过 Django 1.4 表单向导实现(请参阅 处理文件文档)。如果您使用的是 Django 1.3,则可以将新表单向导安装为单独的应用

This isn't possible in the Django 1.3 form wizard. From the Django form wizard docs:

Important limitation: Because the wizard uses HTML hidden fields to store data between pages, you may not include a FileField in any form except the last one

It is possible with the Django 1.4 form wizard (see handling files docs). If you're using Django 1.3, you can install the new form wizard as a separate app.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文