T
T
tosha4encko2019-03-03 17:53:48
Django
tosha4encko, 2019-03-03 17:53:48

How to change file size before saving in model?

My code:

class ...(models.Model):
 ...
  def save(self, *args, **kwargs):
    super(Photo, self).save(*args, **kwargs)

    filepath = self.image.path

    width = self.image.width
    height = self.image.height

    if height < width:
                	new_width = int(round(297*90/25))
                	new_height = int(round(210*90/25))
                else:
                	new_height = int(round(297*90/25))
                	new_width = int(round(210*90/25))

                image = Image.open(filepath)
    image = image.resize((new_width,new_height), Image.ANTIALIAS)
    image.save(filepath, format='JPEG', quality=90)

In general, it works, but I would like to change the size and format before saving, and not after.
I tried to override the save_model method in the admin. There, the file has the TemporaryUploadFile type, how to change its size and type, it was not possible to google it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-03-03
@alternativshik

If the action is frequent, I would look towards the fields for the models from django-imagemagick and not fence the bikes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question