Django file upload
filed in Django, Python on Jul.29, 2007
Some interesting examples on how to handle file uploads using Django:
- Code snippet posted on Djangosnippets. The file is saved by declaring a
save()method in the form class. This method is invoked when callingform.save(), which is standard Django newforms practice. (Note that this snipped usesclean_data. As of Django version 0.96,clean_datahas been renamed tocleaned_data, so you will have to change the code or it won’t work) - Django image upload and validation. The author uses a model for the file and its related data. The uploaded file is saved by calling the
save_FOO_filemethod. (This method is automatically provided by Django for fields declared asmodels.ImageFieldormodels.FileFieldin the model. See the db-api documentation.) - Django image upload, form_for_instance and monkey-patching. The example code creates a form class from
request.userby callingform_for_instance. The resulting class in then monkey-patched to insert the avatar image validation code. (Although the code is interesting the monkey patch seems unnecessary. I wouldn’t mind inserting the avatar validation method in aUserProfileFormclass derived fromform.Forms. The code would be certainly clearer: I think KISS takes precedence over DRY in this case.)
Interesting, there seems to be no easy way of limiting the uploaded file size. The file can be rejected at validation time, but the data would have already been transfered.
A file upload recipe
After reading those posts, I think that a good recipe for handling file uploads in Django would be:
- Write a django model for the uploaded file and its related data. Using a Django model makes sense, because it is usually necessary for the application to keep track of the uploaded files.
- Write a subclass of
form.Formsand declare aclean_FOOmethod for eachmodels.FileInputormodels.ImageInputfields declared in the model class. These clean_FOO methods are used to validate the uploaded files. - use a django view to receive the POST data, or display the form if no data is posted or errors are found.
- validate the uploaded file or files by triggering the standard django newforms validation mechanism:
is_valid(). - save the file or files getting the data directly from the
request.FILESobject, by writing asave()method for the subclassed form or by callingsave_FOO_filefor the model instance.
A simpler way to upload a file
The following short Django example uses no data models, does no data validation, and saves the file directly to disk using python standard file functions. It is just a simple test I wrote to get familiar with the request.FILES object. This is not production code: it could be used to execute an arbitrary script on the server.
The directory where the file is to be saved must be writable by the user that is running the Django server script. (The example uses MEDIA_ROOT as defined in settings.py.)
file: views.py
from django import http
from django import newforms as forms
from django.shortcuts import render_to_response
from djangotest.settings import MEDIA_ROOT</p>
<p>class SimpleFileForm(forms.Form):
file = forms.Field(widget=forms.FileInput, required=False)</p>
<p>def directupload(request):
"""
Saves the file directly from the request object.
Disclaimer: This is code is just an example, and should
not be used on a real website. It does not validate
file uploaded: it could be used to execute an
arbitrary script on the server.
"""</p>
<pre><code>template = 'fileupload.html'
if request['method'] == 'POST':
if 'file' in request.FILES:
file = request.FILES['file']
# Other data on the request.FILES dictionary:
# filesize = len(file['content'])
# filetype = file['content-type']
filename = file['filename']
fd = open('%s/%s' % (MEDIA_ROOT, filename), 'wb')
fd.write(file['content'])
fd.close()
return http.HttpResponseRedirect(' upload_success.html')
else:
# display the form
form = SimpleFileForm()
return render_to_response(template, { 'form': form })
</code></pre>
<p>
file: fileupload.html
{% extends "base.html" %}</p>
<p>{% block body %}</p>
<h1>Upload a file</h1>
<pre><code> <form action="." method="post" enctype="multipart/form-data">
{{ form }}
<input type="submit" value="Upload" />
</form>
</code></pre>
<p>{% endblock %}



August 22nd, 2007 on 9:25 am
Excellent code. It helps me a lot, thank you
April 14th, 2008 on 1:12 pm
Seems like it doesn’t work with 0.96.1. Any ideas why?
April 14th, 2008 on 3:22 pm
What exactly does not work? Do you get any error messages?
May 6th, 2008 on 2:47 am
I think it’s better to use request.method instead of request['method']. At least it is documented in first place:
http://www.djangoproject.com/documentation/request_response/#attributes
May 28th, 2008 on 10:37 pm
Many thanks!!!!
May 30th, 2008 on 11:37 pm
[...] Django file upload | zoia.org (tags: djagnotutorial) [...]
June 13th, 2008 on 1:38 pm
Actually using django to handle file uploads at all is a very bad idea. The problem is that django doesn’t buffer the file out to the disk it just loads the whole thing into RAM. Get a couple of people uploading a 5 meg file at the same time…. and well you’re totally screwed unless your running one of those Sun T2’s with 32 GB or RAM. You can mitigate this to some extent by setting the apache POST limit but that’s only if you have control over that and know for certain that you’ll never get a post larger than X.
There is work on a patch taking place… http://code.djangoproject.com/ticket/2070 but alas it’s been 2 years… and it appears the core team has little to no interest in it.
July 15th, 2008 on 2:13 pm
[...] 7-15-08 Found a better example http://www.zoia.org/blog/2007/07/29/django-file-upload/ « Could not get lock /var/lib/dpkg/lock – open (11 Resource temporarily [...]
July 31st, 2008 on 8:16 am
for the function save_FOO_file(filename, content) the ‘content’ attribute does not exist anymore, use the attribute ‘data’
the request.File is now handled by the InMemoryUploadedFile class, and the raw file is called ‘data’
August 21st, 2008 on 1:21 pm
With regards to MOJAVEs comment, this has been fixed for Django 1.0. Check the documentation at http://www.djangoproject.com/documentation/upload_handling/
June 5th, 2009 on 4:15 pm
I get this error,
Error: One or more models did not validate: polls.poll: “file”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ .
June 5th, 2009 on 8:54 pm
It is as the error message says. You need to install the Python Imaging Library (PIL).
June 8th, 2009 on 5:21 pm
I did install PIL library through python setup.py install command. It still says me the same thing.
Any thoughts?
June 9th, 2009 on 9:37 am
Let me do some testing…
October 30th, 2009 on 2:47 pm
@mojave
it only puts the whole file in RAM if you use .read()
this is from the docs and will work better.