Django:将上传的文件保存到FileField
我觉得不得不问这个有点愚蠢……但我似乎在任何地方都找不到它的记录。
如果我有一个带有 FileField
的 Model
,如何将上传的 FILE
填充到该 FileField
中?
例如,我想做这样的事情:
class MyModel(Model):
file = FileField(...)
def handle_post(request, ...):
mymodel = MyModel.objects.get(...)
if request.FILES.get("newfile"):
mymodel.file = request.FILES["newfile"]
但这似乎不起作用。
I feel a little stupid for having to ask this… But I can't seem find it documented anywhere.
If I've got a Model
with FileField
, how can I stuff an uploaded FILE
into that FileField
?
For example, I'd like to do something like this:
class MyModel(Model):
file = FileField(...)
def handle_post(request, ...):
mymodel = MyModel.objects.get(...)
if request.FILES.get("newfile"):
mymodel.file = request.FILES["newfile"]
But that doesn't appear to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我的怀疑得到了证实:我是个白痴:)
我在问题中概述的方法实际上是正确的 - 它不起作用,因为我忘记包含
enctype="multipart/form-data表单上的“
。无论如何,我会把这个问题留在这里,以防其他人也遇到同样的问题。
Well, my suspicions were confirmed: I am an idiot :)
The method I outline in my question is, in fact, correct — it wasn't working because I'd forgotten to include
enctype="multipart/form-data"
on the form.Anyway, I'll leave this question here, just incase other people have the same problem.
当输入标记中未指定名称属性时,我还遇到了文件未真正发布到服务器的问题
I also had issues with file not really posted to server when name attribute was not specified in input tag