ThumbnailerImageField saves incorrect width_field and height_field when resize_source is applied
michelts opened this issue · 3 comments
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:
- once in the ThumbnailerImageField.save method, in this case, with the correct dimensions.
- once more after that, with the original dimensions, although I couldn't find where this is happening yet.
I'm using Django==3.0.5 and easy-thumbnails==2.7.
I can reproduce this issue. It's really anoying for my use cases. Would it be possible to have a fix ?
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
I used a workaround but your way is more elegant, thank you :)