class ExtendedImageField models ImageField Extended ImageField which c

 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
class ExtendedImageField(models.ImageField):
"""
Extended ImageField which can resize image before saving it,
also gives a random name to image.
"""
def __init__(self, *args, **kwargs):
self.width = kwargs.pop('width', None)
self.height = kwargs.pop('height', None)
super(ExtendedImageField,self).__init__(*args, **kwargs)
def generate_filename(self, instance, filename):
filename_ext = filename.split(".")[-1]
filename_name = md5.new(str(time.time())).hexdigest()
filename = "%s.%s" % (filename_name, filename_ext)
return os.path.join(self.get_directory_name(), self.get_filename(filename))
def save_form_data(self, instance, data):
if data and isinstance(data, UploadedFile):
image = Image.open(StringIO.StringIO(data.read()))
image.thumbnail((self.width, self.height),resample=Image.ANTIALIAS)
getattr(instance, self.name).save(data.name, image, save=False)
def get_internal_type(self):
return 'ImageField'