Skip to content

Instantly share code, notes, and snippets.

@dokterbob
Created August 31, 2011 15:03

Revisions

  1. Mathijs de Bruin revised this gist Aug 31, 2011. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions validators.py
    Original file line number Diff line number Diff line change
    @@ -26,10 +26,10 @@ class FileValidator(object):
    """

    extension_message = _("Extension '%(extension)s' not allowed. Allowed extensions: '%(allowed_extensions)s'")
    mime_message = _("MIME type '%(mimetype)s' is not valid. Allowed types: %(allowed_mimetypes)s")
    min_size_message = _('The current file %(size)s, which is too small. The minumum file size is %(allowed_size)s')
    max_size_message = _('The current file %(size)s, which is too large. The maximum file size is %(allowed_size)s')
    extension_message = _("Extension '%(extension)s' not allowed. Allowed extensions are: '%(allowed_extensions)s.'")
    mime_message = _("MIME type '%(mimetype)s' is not valid. Allowed types are: %(allowed_mimetypes)s.")
    min_size_message = _('The current file %(size)s, which is too small. The minumum file size is %(allowed_size)s.')
    max_size_message = _('The current file %(size)s, which is too large. The maximum file size is %(allowed_size)s.')

    def __init__(self, *args, **kwargs):
    self.allowed_extensions = kwargs.pop('allowed_extensions', None)
  2. Mathijs de Bruin revised this gist Aug 31, 2011. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions validators.py
    Original file line number Diff line number Diff line change
    @@ -19,6 +19,11 @@ class FileValidator(object):
    max_size: maximum number of bytes allowed
    ie. 24*1024*1024 for 24 MB
    Usage example::
    MyModel(models.Model):
    myfile = FileField(validators=FileValidator(max_size=24*1024*1024), ...)
    """

    extension_message = _("Extension '%(extension)s' not allowed. Allowed extensions: '%(allowed_extensions)s'")
  3. Mathijs de Bruin revised this gist Aug 31, 2011. 1 changed file with 3 additions and 5 deletions.
    8 changes: 3 additions & 5 deletions validators.py
    Original file line number Diff line number Diff line change
    @@ -2,14 +2,12 @@

    from django.core.exceptions import ValidationError
    from django.utils.translation import ugettext_lazy as _
    from django.forms.fields import FileField
    from django.template.defaultfilters import filesizeformat


    class FileValidator(object):
    """
    Subclass of the FileField form field which optionally checks the
    extension, mimetype and size of the uploaded files.
    Validator for files, checking the size, extension and mimetype.
    Initialization parameters:
    allowed_extensions: iterable with allowed file extensions
    @@ -39,7 +37,7 @@ def __call__(self, value):
    Check the extension, content type and file size.
    """
    # Check the extension
    ext = splitext(value)[1][1:].lower()
    ext = splitext(value.name)[1][1:].lower()
    if self.allowed_extensions and not ext in self.allowed_extensions:
    message = self.extension_message % {
    'extension' : ext,
    @@ -60,7 +58,7 @@ def __call__(self, value):

    # Check the file size
    filesize = value.file._size
    if filesize > self.max_size:
    if self.max_size and filesize > self.max_size:
    message = self.max_size_message % {
    'size': filesizeformat(filesize),
    'allowed_size': filesizeformat(self.max_size)
  4. Mathijs de Bruin renamed this gist Aug 31, 2011. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  5. Mathijs de Bruin revised this gist Aug 31, 2011. 1 changed file with 2 additions and 8 deletions.
    10 changes: 2 additions & 8 deletions snippet.sc
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,7 @@ from django.forms.fields import FileField
    from django.template.defaultfilters import filesizeformat


    class ValidatingFileField(FileField):
    class FileValidator(object):
    """
    Subclass of the FileField form field which optionally checks the
    extension, mimetype and size of the uploaded files.
    @@ -34,14 +34,10 @@ class ValidatingFileField(FileField):
    self.min_size = kwargs.pop('min_size', 0)
    self.max_size = kwargs.pop('max_size', None)

    super(ValidatingFileField, self).__init__(*args, **kwargs)

    def clean(self, value):
    def __call__(self, value):
    """
    Check the extension, content type and file size.
    """
    value = super(ValidatingFileField, self).clean(value)

    # Check the extension
    ext = splitext(value)[1][1:].lower()
    if self.allowed_extensions and not ext in self.allowed_extensions:
    @@ -79,5 +75,3 @@ class ValidatingFileField(FileField):
    }

    raise ValidationError(message)

    return value
  6. Mathijs de Bruin created this gist Aug 31, 2011.
    83 changes: 83 additions & 0 deletions snippet.sc
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,83 @@
    from os.path import splitext

    from django.core.exceptions import ValidationError
    from django.utils.translation import ugettext_lazy as _
    from django.forms.fields import FileField
    from django.template.defaultfilters import filesizeformat


    class ValidatingFileField(FileField):
    """
    Subclass of the FileField form field which optionally checks the
    extension, mimetype and size of the uploaded files.
    Initialization parameters:
    allowed_extensions: iterable with allowed file extensions
    ie. ('txt', 'doc')
    allowd_mimetypes: iterable with allowed mimetypes
    ie. ('image/png', )
    min_size: minimum number of bytes allowed
    ie. 100
    max_size: maximum number of bytes allowed
    ie. 24*1024*1024 for 24 MB
    """

    extension_message = _("Extension '%(extension)s' not allowed. Allowed extensions: '%(allowed_extensions)s'")
    mime_message = _("MIME type '%(mimetype)s' is not valid. Allowed types: %(allowed_mimetypes)s")
    min_size_message = _('The current file %(size)s, which is too small. The minumum file size is %(allowed_size)s')
    max_size_message = _('The current file %(size)s, which is too large. The maximum file size is %(allowed_size)s')

    def __init__(self, *args, **kwargs):
    self.allowed_extensions = kwargs.pop('allowed_extensions', None)
    self.allowed_mimetypes = kwargs.pop('allowed_mimetypes', None)
    self.min_size = kwargs.pop('min_size', 0)
    self.max_size = kwargs.pop('max_size', None)

    super(ValidatingFileField, self).__init__(*args, **kwargs)

    def clean(self, value):
    """
    Check the extension, content type and file size.
    """
    value = super(ValidatingFileField, self).clean(value)

    # Check the extension
    ext = splitext(value)[1][1:].lower()
    if self.allowed_extensions and not ext in self.allowed_extensions:
    message = self.extension_message % {
    'extension' : ext,
    'allowed_extensions': ', '.join(self.allowed_extensions)
    }

    raise ValidationError(message)

    # Check the content type
    mimetype = value.file.content_type
    if self.allowed_mimetypes and not mimetype in self.allowed_mimetypes:
    message = self.mime_message % {
    'mimetype': mimetype,
    'allowed_mimetypes': ', '.join(self.allowed_mimetypes)
    }

    raise ValidationError(message)

    # Check the file size
    filesize = value.file._size
    if filesize > self.max_size:
    message = self.max_size_message % {
    'size': filesizeformat(filesize),
    'allowed_size': filesizeformat(self.max_size)
    }

    raise ValidationError(message)

    elif filesize < self.min_size:
    message = self.min_size_message % {
    'size': filesizeformat(filesize),
    'allowed_size': filesizeformat(self.min_size)
    }

    raise ValidationError(message)

    return value