Django file upload

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 calling form.save(), which is standard Django newforms practice. (Note that this snipped uses clean_data. As of Django version 0.96, clean_data has been renamed to cleaned_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_file method. (This method is automatically provided by Django for fields declared as models.ImageField or models.FileField in 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.user by calling form_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 a UserProfileForm class derived from form.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.Forms and declare a clean_FOO method for each models.FileInput or models.ImageInput fields 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.FILES object, by writing a save() method for the subclassed form or by calling save_FOO_file for 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> &lt;form action="." method="post" enctype="multipart/form-data"&gt;
         {{ form }}
         &lt;input type="submit" value="Upload" /&gt;
 &lt;/form&gt;
</code></pre>

<p>{% endblock %}


Comments (15)

Harry Potter y el trabajo en equipo

Varios grupos de fans ya han traducido Harry Potter and the Deathly Hallows a varios idiomas. HarryLatino comenta de dos traducciones al castellano, y también hay alguna traducción al alemán.

Gracias a Internet, no es difícil repartirse el trabajo de traducir entre varias personas. Uno o dos pueden coordinar el esfuerzo. Como si fueran varias computadoras trabajando en paralelo. La pregunta que se hace tanta gente: ¿por qué demoran tanto en salir las traducciones oficiales? Hubieran aprovechado todo el marketing que se hizo para el lanzamiento en inglés.

En Lima están vendiendo el libro en inglés desde el mismo 21 de julio. No tiene pierde. Va a ser todo un reto para los que hagan la película.


Leave a Comment

Django newforms documentation updated

The Django newforms documentation has been updated some days ago. It includes an explanation on how to use form_for_models and form_for_instance and provides some examples.

More interesting, however, is when not to use them: “If you want to create a form whose fields map to more than one model, or a form that contains fields that aren’t on a model, you shouldn’t use these shortcuts.”


Leave a Comment