Skip to content

Instantly share code, notes, and snippets.

@victorono
Created April 9, 2014 21:24
Show Gist options
  • Save victorono/10318379 to your computer and use it in GitHub Desktop.
Save victorono/10318379 to your computer and use it in GitHub Desktop.
File Mimetype Validator

This validator works well with FileField form fields and can validate that an uploaded file has an acceptable mimetype. Place this snippet in your app's validators.py.

Requirements:

This snippet uses python-magic. To install:

pip install python-magic

from validators import MimetypeValidator
class MyForm(forms.Form):
file = forms.FileField(
allow_empty_file=False,
validators=[MimetypeValidator('application/pdf')],
help_text="Upload a PDF file"
)
from django.core.exceptions import ValidationError
import magic
class MimetypeValidator(object):
def __init__(self, mimetypes):
self.mimetypes = mimetypes
def __call__(self, value):
try:
mime = magic.from_buffer(value.read(1024), mime=True)
if not mime in self.mimetypes:
raise ValidationError('%s is not an acceptable file type' % value)
except AttributeError as e:
raise ValidationError('This value could not be validated for file type' % value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment