mwo
mwo

Reputation: 85

Django - Uploaded image gets saved twice: under original and validated name

I'm trying to solve a problem. On image file upload, I want to rename the file and resize it. I came up with a method below. I managed to get the image resized and saved under a valid name.

Unfortunately the file gets saved twice, also under the invalid name. And the invalid one is stored in my object. How can I fix this? Thanks in advance

class SparePartImages(models.Model):
  sparepart = models.ForeignKey('SparePart', on_delete=models.CASCADE)
  image = models.ImageField(upload_to='spare-part/', blank=True, null=True)

  def save(self, *args, **kwargs):
    super(SparePartImages, self).save(*args, **kwargs)
    max_size = settings.IMAGE_MAX_SIZE
    file = Image.open(self.image)
    (width, height) = file.size
    if (width/max_size < height/max_size):
      factor = height/max_size
    else:
      factor = width/max_size
    size = (int(width/factor), int(height/factor))
    file = file.resize(size, Image.ANTIALIAS)

    file.save(removeAccent(self.image.path))

Upvotes: 0

Views: 105

Answers (1)

Ahtisham
Ahtisham

Reputation: 10116

You are calling save twice one with super and other with save to fix it do this:

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import sys

class SparePartImages(models.Model):
 # rest of the code
 def save(self, *args, **kwargs):
   # rest of the code 
   # but remove file.save(removeAccent(self.image.path))
   output = BytesIO()
   file.save(output, format='JPEG', quality=100)
   output.seek(0)
   self.image = InMemoryUploadedFile(
      output ,'ImageField', "%s.jpg" %self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None
   )
   super(SparePartImages, self).save(*args, **kwargs)

Upvotes: 1

Related Questions