Django:将上传的文件保存到FileField

时间:2022-07-13 19:16:16

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?

如果我有一个带有FileField的模型,我如何将上传的FILE填充到该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.

但这似乎不起作用。

2 个解决方案

#1


16  

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.

我在问题中概述的方法实际上是正确的 - 它没有用,因为我忘了在表单上包含enctype =“multipart / form-data”。

Anyway, I'll leave this question here, just incase other people have the same problem.

无论如何,我会在这里留下这个问题,只是因为其他人也有同样的问题。

#2


0  

I also had issues with file not really posted to server when name attribute was not specified in input tag

当输入标记中未指定name属性时,我也遇到过没有真正发布到服务器的文件的问题

<input type="file" name="somename">

#1


16  

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.

我在问题中概述的方法实际上是正确的 - 它没有用,因为我忘了在表单上包含enctype =“multipart / form-data”。

Anyway, I'll leave this question here, just incase other people have the same problem.

无论如何,我会在这里留下这个问题,只是因为其他人也有同样的问题。

#2


0  

I also had issues with file not really posted to server when name attribute was not specified in input tag

当输入标记中未指定name属性时,我也遇到过没有真正发布到服务器的文件的问题

<input type="file" name="somename">