Validating File uploads in Django 1.0

While working on Clapton, the Django-based Content Management System (CMS), I had to write validation code for file uploads. This is needed because Clapton contains applications specific to media types such as documents which requires Word Documents, PDFs or OpenDocumentFormat files, and podcasts which requires MP3 or OGG files. But how do you guarantee that the right files are uploaded? By using Django’s custom fields and newforms module.

The following code creates a DocumentField class that only accepts Word, Text, RTFs, HTML, PDF or ODF files:

[gist 5942532]

When a DocumentField object is used in a custom form and the form is being validated, the clean method is called.

First, it calls the FileField‘s clean method which validates the field using the FileField validation criteria. Then it constructs two tuples file_types and file_exts containing the valid content-types and the valid file extensions. The data argument is check against the content-types, which are taken from the IANA MIME Media Types page (content-type information for files is sent along with any HTTP file upload).

Quite simple. To turn this into an image validator for PNG files, change the file_exts to ('image/png') and file_types to ('.png').

Just toss that code into your application file, create a custom form and insert the field and that’s it.

Click here for more information on the Django Forms API.

Comments are Closed