Skip to content

Instantly share code, notes, and snippets.

@gregmuellegger
Created July 23, 2012 12:54
Show Gist options
  • Save gregmuellegger/3163489 to your computer and use it in GitHub Desktop.
Save gregmuellegger/3163489 to your computer and use it in GitHub Desktop.
FileTypeValidator
import re
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
class FileTypeValidator(object):
error_message = _(u'Please upload a file of the correct type.')
def __init__(self, regex, error_message=None):
self.regex = re.compile(regex)
if self.error_message is not None:
self.error_message = error_message
def __call__(self, value):
import magic
try:
if not hasattr(value, 'read'):
raise ValidationError(self.error_message)
filetype = magic.from_buffer(value.read())
if not self.regex.match(filetype):
raise ValidationError(self.error_message)
finally:
if hasattr(value, 'seek'):
value.seek(0)
pdf_validator = FileTypeValidator(r'^PDF document.*$',
error_message=_(u'Bitte laden Sie eine PDF Datei hoch.'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment