Created
July 23, 2012 12:54
-
-
Save gregmuellegger/3163489 to your computer and use it in GitHub Desktop.
FileTypeValidator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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