Django CookBook: File type validation in form

The snippet will validate a file uploaded against a list of accepted content types.

# Tested in Django 1.6
class ImportForm(forms.Form):
    csv_file = forms.FileField(label=_('Select CSV file'))
    def clean_csv_file(self):
        f = self.cleaned_data['csv_file']
        if not f.content_type in ['text/csv',]:
            raise forms.ValidationError(_("The file type is not accepted."))
        return f

View Gist

< / >