有人知道 Django 中文件上传的最新(2009 年 9 月)示例吗?
更新:由于下面的海报,很明显官方文档是最新的。最好仔细阅读,而不是浏览谷歌中出现的一堆其他页面。
我一直在寻找在 Django 中上传文件的示例和片段,但后来读到人们说它们已经过时了。
以下是我在网络上的基本困惑(通过查看各种示例)。
我是否必须自己手动保存文件数据(即打开文件并写入,如 这个示例)或者当我保存具有文件类型字段的模型时,Django 现在会自动保存文件吗?
我是否必须手动从某处获取文件数据才能将其复制到模型中的此字段?我的意思是,我知道 request.FILES 已被弃用),但是当我从自定义 HTML 表单(使用
欢呼
菲尔
UPDATE : thanks to posters below, it's clear that the official documentation is up-to-date. Best to read that carefully rather than skim a bunch of other pages that turn up in Google.
I keep finding examples and snippets for uploading files in Django, but then reading people saying that they're out of date.
Here are my basic confusions (from seeing various examples) around the web.
Do I have to save the file data myself manually (ie. open a file and write it, as in this example) or does Django now save the file automatically when I save a model which has a field of type File?
Do I have to manually get the file data from somewhere in order to copy it in to this field in the model? I mean, I understand that request.FILES is deprecated) but when I upload a file from a custom HTML-form (using a <input type="file" tag) the cleaned_data for this field is None, even though the request.FILES dictionary still seems to contain the data. So how am I meant to pick up the file data and put it into the model's field? (If that's what I'm meant to do?)
cheers
phil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
文档非常好关于这一点,并且是最新的。
对于基本文件上传,只需使用
FileField
在您的表单中。将request.POST
和request.FILES
传递到此表单将为您完成这项工作。当然,据我所知,request.FILES
并未被弃用。现在,如果您想对文件上传做更多奇特的事情,那就是您必须摆脱默认的
FileField
的情况,但同样,这在 文档。我还要补充一点,一个常见的错误是忘记在表单中包含
enctype="multipart/form-data"
。不包含此内容会导致request.FILES
为空。The docs are very good regarding this, and are up-to-date.
For basic file uploading, simply use a
FileField
in your form. Passing inrequest.POST
andrequest.FILES
to this form will do the work for you. Certainly,request.FILES
is not deprecated as far as I can tell.Now, if you want to do more fancy stuff with your file uploads, that is when you'll have to potentially break away from the default
FileField
, but again, this is covered quite well in the documentation.I will also add that one common mistake is forgetting to have
enctype="multipart/form-data"
in one's form. Not including this results inrequest.FILES
being empty.