I have the following Image model
class Image(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to=image_path, max_length=300,blank=True) thumbnail=models.ImageField(upload_to=image_thumb_path,max_length=300, blank=True)
And I need to implement the following behavior for this model:
- When loading an image field, create a thumbnail and save it in the thumbnail field.
- When deleting the image field, also delete the thumbnail.
- When deleting a thumbnail… just delete the thumbnail
To implement this I override the save method like here
def save(self, *args, **kwargs) -> None: THUMBNAIL_SIZE = (400, 400) if self.image: image = PILImage.open(self.image) image = image.convert("RGB") image.thumbnail(THUMBNAIL_SIZE, PILImage.ANTIALIAS) temp_thumb = BytesIO() image.save(temp_thumb, "JPEG") temp_thumb.seek(0) self.thumbnail.save( self.image.name, ContentFile(temp_thumb.read()), save=False, ) temp_thumb.close() elif self.thumbnail and not self.image: self.thumbnail.delete() return super().save( *args, **kwargs)
As you can see it matches the first two conditions but I don’t know how to implement the 3rd condition because every time I delete the thumbnail it creates it again because 1st condition. What wrong here? It seems to be impossible to implement because the conditions for 1 and 3 tasks are the same