from StringIO import StringIO from django db import models from django

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from StringIO import StringIO
from django.db import models
from django.core.files.uploadedfile import SimpleUploadedFile
from util import resize_image
class ExtendedImageField(models.ImageField):
"""
Extended ImageField which can resize image before saving it.
"""
def __init__(self, *args, **kwargs):
self.width = kwargs.pop('width', None)
self.height = kwargs.pop('height', None)
super(ExtendedImageField, self).__init__(*args, **kwargs)
def get_save_FIELD_file(self):
def _save_FIELD_file(instance, filename, raw_field, save=True):
"""
Resize on the fly raw contents of field and call parent save_field
method.
"""
if self.width and self.height:
raw_contents = resize_image(rawdata=raw_field.read(),
width=self.width,
height=self.height)
raw_field = SimpleUploadedFile(raw_field.name,
raw_contents,
raw_field.content_type)
instance._save_FIELD_file(self, filename, raw_field, save)
return _save_FIELD_file
def contribute_to_class(self, cls, name):
super(ExtendedImageField, self).contribute_to_class(cls, name)
# overwrite parent binding to 'save_%s_file'
setattr(cls, 'save_%s_file' % self.name, self.get_save_FIELD_file())
#def get_internal_type(self):
# return 'ImageField'