File type validation in Django forms

In this article, I'm using the Python Magic library to check for file types in form validation.

If you are developing on OSX, you will need to install libmagic first. The best way I found is with Homebrew.

$ brew install libmagic

Then you can install python-magic using the usual pip:

$ pip install python-magic

Using Magic in a Django form:

import magic
...
class myForm(forms.Form):
    file = forms.FileField()
    def clean_file(self):
        file = self.cleaned_data['file']
        mime = magic.from_buffer(file.read(), mime=True)
        if not mime == 'application/pdf':
            raise forms.ValidationError('File must be a PDF document')
        else:
            return file

The above validator will only accept PDF document, looking at the mime type of the file, which is a stronger validation than looking at the filename prefix, which I have seen in many other validators.

< / >