Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top