I am trying to overwrite the save function. What I want is to resize the original photos to a default size (800 * 534) and then to generate a thumbnails for this picture. However, I found the photos were stored twice.
For example, I add a photo named sample.jpg at first time. There are three photos in my directions. One is in ../Media/photos/ and the others are in ../Media/. When I save this picture again, there are four photos. Two are in ../Media/photos/, and the others are in ../Media/.
I am really confused why Django stores the picture twice and why my pictures were stored in ../Media not in ../Media/photos. What I want is to make only two pictures which the 800*534 picture and its thumbnail picture in ../Media/photos.
Here are my codes.
The class Photo:
class Photo(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
summary = models.TextField(blank=True)
created_date = models.DateField(auto_now_add=True)
modified_date = models.DateField(auto_now=True)
image = models.ImageField(upload_to='photo/')
album = models.ForeignKey(Album, on_delete=models.CASCADE)
is_cover_photo = models.BooleanField(default=False)
The save function I wrote in class Photo
def save(self):
if not self.pk:
filename = self.image
if filename:
print(filename)
img = Image.open(filename)
# save the default size photo
default_size = (800, 534)
img.thumbnail(default_size, Image.ANTIALIAS)
img.save(self.get_img_filename(filename))
# save thumbnail photo
cover_size = (342, 229)
img.thumbnail(cover_size, Image.ANTIALIAS)
img.save(self.get_img_thumb_filename(filename))
super(Photo, self).save()
And the other two functions:
def get_img_filename(self, img):
return img.path
def get_img_thumb_filename(self, img):
img_pre, img_ext = os.path.splitext(img.path)
thumb_name = img_pre + '_thumb' + img_ext
return thumb_name