有人知道 Django 中文件上传的最新(2009 年 9 月)示例吗?

发布于 2024-08-05 22:05:30 字数 447 浏览 2 评论 0原文

更新:由于下面的海报,很明显官方文档是最新的。最好仔细阅读,而不是浏览谷歌中出现的一堆其他页面。


我一直在寻找在 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 技术交流群。

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

发布评论

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

评论(1

我不会写诗 2024-08-12 22:05:30

文档非常好关于这一点,并且是最新的。

对于基本文件上传,只需使用 FileField 在您的表单中。将 request.POSTrequest.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 in request.POST and request.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 in request.FILES being empty.

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