I am looking for a way to resize, compress, and optimize the uploaded image when saving an ImageField.
class Image(models.Model):
name = models.CharField(max_length=254, blank=True)
caption = models.TextField(max_length=1000, blank=True)
height = models.IntegerField()
width = models.IntegerField()
image = models.ImageField(upload_to='', height_field='height', width_field='width', storage=S3MediaStorage())
My first thought was to override the model's save()
and implement this logic there, but I don't want the resize/compression/optimization to run again if the user doesn't update the image file (i.e. if he only updates name
or caption
on an existing object and saves it).
What is a proper way to check when a new image file is uploaded to the ImageField, but not when the user only changes another field in the Model, eg. the user updates
caption
but leaves everything else as-is?How can the uploaded image file be accessed in code? I.e. what is the variable that contains the actual image file that can be passed to Pillow?
edit: This is unique from the suspected duplicate. I am not asking if the field has changed, because that would always cause false positives. I am asking if the user has uploaded an image file, which I will immediately change (resize/optimize/compress), so if the user immediately downloads his uploaded image he'll find that has a different binary with a randomly generated filename, and therefore comparing the filename or binary are not valid methods to determine if the user is uploading a different image.