Upload Image + Making thumbs

 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
class Picture(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=50)
picture = models.ImageField(upload_to="upload/images/")
thumbnail = models.ImageField(upload_to="upload/images/thumbnails/", editable=False, blank=True)
def save(self):
if not self.thumbnail:
from PIL import Image
MAX_WIDTH = 590
MAX_HEIGHT = 400
THUMBNAIL_SIZE = (MAX_WIDTH, MAX_HEIGHT)
image = Image.open(self.get_picture_filename())
image_size = image.size
if image_size[0]>MAX_WIDTH | image_size[1]>MAX_HEIGHT:
self.save_thumbnail_file(self.get_picture_filename(), '')
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
image.save(self.get_thumbnail_filename())
super(Picture, self).save()