Django表单文件字段在表单错误消失 [英] Django Form File Field disappears on form error

查看:127
本文介绍了Django表单文件字段在表单错误消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题,我有一个包含文件字段的Django表单,即:

  photo = forms.FileField help_text =请附加照片,required = False)

如果表单验证,则文件字段有界和正确保存。 问题是当用户填写所有表单并且不验证时:所选文件的路径消失



所以,如果用户没有意识到这一点,他/她修复了其他字段错误并再次提交 - 这次没有照片。



以防万一,表单被创建在这样的视图中:

  ProfileForm(request.POST或None,request.FILES或None)

,HTML是:

 < div id =uniform-id_photoclass =uploader> 
< input id =id_photoclass =clearablefileinputtype =filename =photosize =19style =opacity:0;>
< span class =filenamestyle = - moz-user-select:none;>未选择文件< / span>
< span class =actionstyle = - moz-user-select:none;>选择文件< / span>
< / div>

有没有人有同样的问题吗?对解决方案的任何想法? :$



谢谢!

解决方案

不幸的是,这是一个问题(真的是一个安全功能)由浏览器强加,并且是不可解决的。浏览器不会让您指定文件输入的初始值,并且您无法解决这个问题。



原因是如果一个网站可以这样做,它会打开一个向量,允许任何网站通过猜测文件路径窃取您的计算机上的任何文件 - 他们可能只有一个脚本在后台运行,试图将有趣的文件发送回服务器。 / p>

唯一的解决方法是将上传的文件实际保存在服务器上,而不管表单是否验证,然后将表单和错误呈现给用户时,表示您已收到一个文件,他们应该只填写该字段来替换它。


Here is the problem, I have a Django Form containing a File field, namely:

photo = forms.FileField(help_text="Please attach a photo", required=False)

If the form validates, the File field is bounded and saved correctly. The problem is when the user fills all the form and it doesn't validate: the path of the selected file disappear.

So, if the user doesn't realize about this, he/she fix the other fields errors and submit again - with no photo this time.

Just in case, the form is created in the view like this:

ProfileForm(request.POST or None, request.FILES or None)

and the HTML is:

<div id="uniform-id_photo" class="uploader">
  <input id="id_photo" class="clearablefileinput" type="file" name="photo" size="19" style="opacity: 0;">
  <span class="filename" style="-moz-user-select: none;">No file selected</span>
  <span class="action" style="-moz-user-select: none;">Choose File</span>
</div>

Has anyone had the same problem before? Any thoughts towards a solution? :)

Thanks!

解决方案

Unfortunately, this is a problem (really a security feature) imposed by browsers, and is not solvable, as such. Browsers will not let you specify an initial value for file inputs, and there's nothing that you will be able to do to work around that.

The reason is that if a website could do this, it would open up a vector that would allow any website to steal any file on your computer by guessing file paths--they could just have a script running in the background that tried to post interesting files back to the server.

The only workaround is to actually save the uploaded file on the server regardless of whether the form validates, and then when you render the form and errors back to the user, indicate that you have received a file and that they should only fill out that field to replace it.

这篇关于Django表单文件字段在表单错误消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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