Skip to content

Instantly share code, notes, and snippets.

@seanmavley
Forked from chriskief/fields.py
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanmavley/d38ffcac8369e379a7ef to your computer and use it in GitHub Desktop.
Save seanmavley/d38ffcac8369e379a7ef to your computer and use it in GitHub Desktop.
from django import forms
# import models here from django and subclass
from django.db import models
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
class RestrictedFileFieldModel(models.FileField):
def __init__(self, *args, **kwargs):
self.content_types = kwargs.pop('content_types', None)
self.max_upload_size = kwargs.pop('max_upload_size', None)
if not self.max_upload_size:
self.max_upload_size = settings.MAX_UPLOAD_SIZE
super(RestrictedFileField, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super(RestrictedFileField, self).clean(*args, **kwargs)
try:
if data.content_type in self.content_types:
if data.size > self.max_upload_size:
raise forms.ValidationError(_('File size must be under %s. Current file size is %s.') % (filesizeformat(self.max_upload_size), filesizeformat(data.size)))
else:
raise forms.ValidationError(_('File type (%s) is not supported.') % data.content_type)
except AttributeError:
pass
return data
class RestrictedFileField(forms.FileField):
def __init__(self, *args, **kwargs):
self.content_types = kwargs.pop('content_types', None)
self.max_upload_size = kwargs.pop('max_upload_size', None)
if not self.max_upload_size:
self.max_upload_size = settings.MAX_UPLOAD_SIZE
super(RestrictedFileField, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super(RestrictedFileField, self).clean(*args, **kwargs)
try:
if data.content_type in self.content_types:
if data.size > self.max_upload_size:
raise forms.ValidationError(_('File size must be under %s. Current file size is %s.') % (filesizeformat(self.max_upload_size), filesizeformat(data.size)))
else:
raise forms.ValidationError(_('File type (%s) is not supported.') % data.content_type)
except AttributeError:
pass
return data
class RestrictedImageField(forms.ImageField):
def __init__(self, *args, **kwargs):
self.max_upload_size = kwargs.pop('max_upload_size', None)
if not self.max_upload_size:
self.max_upload_size = settings.MAX_UPLOAD_SIZE
super(RestrictedImageField, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super(RestrictedImageField, self).clean(*args, **kwargs)
try:
if data.size > self.max_upload_size:
raise forms.ValidationError(_('File size must be under %s. Current file size is %s.') % (filesizeformat(self.max_upload_size), filesizeformat(data.size)))
except AttributeError:
pass
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment