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

查看:39
本文介绍了如何使 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天全站免登陆