class Picture models Model description models TextField big_picture Ex

 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
47
48
49
50
class Picture(models.Model):
description = models.TextField()
big_picture = ExtendedImageField(upload_to="big_picture/%Y/%m/%d/", max_length=100, width=settings.BIG_PICTURE_WIDTH, height=settings.BIG_PICTURE_HEIGHT)
middle_picture = models.ImageField(upload_to="middle_picture/%Y/%m/%d", blank=True, editable=False, max_length=100)
small_picture = models.ImageField(upload_to="small_picture/%Y/%m/%d", blank=True, editable=False, max_length=100)
def save_picture(self, image, directory, path):
date = datetime.date.today()
name = os.path.basename(path)
year = str(date.year)
month = str(date.month).zfill(2)
day = str(date.day).zfill(2)
abs_path = os.path.join(settings.MEDIA_ROOT, directory, year, month, day)
rel_path = os.path.join(directory, year, month, day)
if not os.path.isdir(abs_path):
os.makedirs(abs_path)
image.save("%s/%s" % (abs_path, name))
return "%s/%s" % (rel_path, name)
def create_middle(self, path):
image = Image.open(path)
size = (200, 200)
image.thumbnail(size, Image.ANTIALIAS)
return self.save_picture(image, settings.MIDDLE_PICTURE, path)
def create_small(self, path):
image = Image.open(path)
x,y = image.size
min_size = min(x, y)
region = image.crop((0, 0, min_size, min_size))
size = (100, 100)
region.thumbnail(size, Image.ANTIALIAS)
return self.save_picture(region, settings.SMALL_PICTURE, path)
def save(self):
if self.big_picture:
image_path = self.big_picture.path
self.middle_picture = self.create_middle(image_path)
self.small_picture = self.create_small(image_path)
super(Picture, self).save()
class Meta:
verbose_name = "Picture"
verbose_name_plural = "Pictures"
def __unicode__(self):
return self.description