SmileyChris / easy-thumbnails

Easy thumbnails for Django
http://easy-thumbnails.readthedocs.org/
BSD 3-Clause "New" or "Revised" License
1.37k stars 312 forks source link

ThumbnailerImageField saves incorrect width_field and height_field when resize_source is applied #548

Open michelts opened 3 years ago

michelts commented 3 years ago

Consider the following snippet:

    image_width = models.PositiveIntegerField()
    image_height = models.PositiveIntegerField()
    image = ThumbnailerImageField(
        width_field="image_width",
        height_field="image_height",
        resize_source={"size": (100, 100)},
    )

When I save an instance of the model with this field, the image_field and image_height fields are populated with the original image size rather than the thumbnail size.

I couldn't find why this is happening, but after activating a higher level of debugging, I found that the object is saved twice:

I'm using Django==3.0.5 and easy-thumbnails==2.7.

Akiat commented 3 years ago

I can reproduce this issue. It's really anoying for my use cases. Would it be possible to have a fix ?

michelts commented 3 years ago

I personally couldn't find a way to fix it, but I implemented a workaround using a pre-save signal. See it below, assuming you have a model Figure with an attribute image:

@receiver(models.signals.pre_save, sender=Figure)
def resize_image(sender, instance, **kwargs):
    orig_file = io.BytesIO(instance.image.read())
    thumbnailer = get_thumbnailer(orig_file, instance.image.name)
    thumb = thumbnailer.get_thumbnail(options, save=False)
    instance.image.save(instance.image.name, thumb, save=False)
    instance.image_width = thumb.width
    instance.image_height = thumb.height
Akiat commented 3 years ago

I used a workaround but your way is more elegant, thank you :)