1

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
Xiaohang
  • 11
  • 2

2 Answers2

0

This happens because your program is still calling the super class's save method which implicitly saves all the fields, including "image". Therefore, you have duplicated images in your server.

Lukas Herman
  • 170
  • 2
  • 9
0

you can pass a parametter inside the save function like this:

img.save(self.get_img_filename(filename), save=False)

Your problem is that you are PIL.Image is saving the image localy plus in the Model Db you are calling it another save storing it localy like Lukas Herman said. you need a way to store Image into ImageField possible without using PIL.Image.save(). here is a link I found : link-stackoverflow Another Posible Solution is to store using Image Class and store the image and save the path location to CharField or TextField

devcodexyz
  • 65
  • 7