views:

100

answers:

1

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

+3  A: 

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.

Ryan Duffield
+1, the documentation is clear that you need to pass request.FILES when instantiating the form. Can't imagine where the OP got the idea that it was deprecated.
Daniel Roseman
thanks. Yes I missed the request.FILES being passed into the form constructor in the official documentation example. I was reading another site which was showing it being accessed explicitly and a comments saying that this was out-of-date.
interstar
actually. On second thoughts, the file doesn't seem to be saved anywhere. So I do have to do this manually??
interstar
You have to set a MEDIA_ROOT property in your settings pointing to a harddrive location to store files.
Jasconius
Are you calling is_valid() or save() on your form instance?
Ryan Duffield
I guess another question would be; is this a ModelForm or plain Form you are working with?
Ryan Duffield