如何使Django表单在验证失败后保留文件 [英] How to make a Django form retain a file after failing validation

查看:154
本文介绍了如何使Django表单在验证失败后保留文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

form = AddItemForm(request.POST, request.FILES)

if form.is_valid()

   do_stuff

return render_to_response(blah.html, {'form':form})

现在表单将具有错误信息以及字段的原始值,但不保留所选文件
如果表单验证失败,我该如何保留所选文件?

Now form will have the error information along with the original values of the fields, but it does not retain a selected file How do I keep the selected file if the form fails validation?

推荐答案

您想要做的问题是,出于安全考虑,浏览器不允许文件输入框在页面加载时具有预先选择的值。即使它只是保留同一页面上一个实例的值也是如此。没有任何Django可以做到这一点。

The problem with what you want to do is that, for security reasons, browsers will not allow a file input box to have a pre-selected value on page load. This is true even if it is simply preserving the value from a previous instance of the same page. There is nothing Django can do to change this.

如果您想避免要求用户重新选择并重新上传文件,则需要保存即使验证失败,上传的文件,然后将文件输入字段替换为表示您已经拥有数据。您还可能需要运行某些JavaScript的按钮,以便在用户想要放入其他文件时重新启用文件字段。我不认为Django有这样的机器,所以你必须自己编码。

If you want to avoid asking the user to re-select and re-upload the file, you will need to save the uploaded file even when validation fails, and then replace the file input field with something to indicate that you already have the data. You would also probably also want a button that runs some JavaScript to re-enable the file field if the user wants to put in a different file. I don't think Django comes with any machinery for this, so you'll have to code it yourself.

这篇关于如何使Django表单在验证失败后保留文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆