Skip to content

Instantly share code, notes, and snippets.

@solanoize
Created July 1, 2017 08:39
Show Gist options
  • Select an option

  • Save solanoize/e8b0abf4b98a70cab05b5e96a0302a0c to your computer and use it in GitHub Desktop.

Select an option

Save solanoize/e8b0abf4b98a70cab05b5e96a0302a0c to your computer and use it in GitHub Desktop.
from django.db.models import FileField
from django.forms import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
class ImageFieldRestrict(FileField):
def __init__(self, *args, **kwargs):
self.content_types = ['image/jpeg', 'image/gif']
self.max_upload_size = 2242880
super(ImageFieldRestrict, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super(ImageFieldRestrict, self).clean(*args, **kwargs)
file = data.file
try:
content_type = file.content_type
if content_type in self.content_types:
if file._size > self.max_upload_size:
message = 'Please keep filesize under {}. Current file size %s'
message = message.format(filesizeformat(self.max_upload_size), filesizeformat(file._size))
raise forms.ValidationError(_(message))
else:
raise forms.ValidationError(_('Filetype not supported.'))
except AttributeError:
pass
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment