Django: Save an uploaded file to a FileField
Asked Answered
S

2

11

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.

Soupandfish answered 16/5, 2010 at 18:37 Comment(0)
S
19

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.

Soupandfish answered 16/5, 2010 at 18:41 Comment(0)
C
0

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

<input type="file" name="somename">
Carpet answered 9/5, 2013 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.