Skip to content

Instantly share code, notes, and snippets.

@rodrigobertin
Last active December 14, 2022 13:34
Show Gist options
  • Save rodrigobertin/28d6bf1d9d1033ef926e20a1431df267 to your computer and use it in GitHub Desktop.
Save rodrigobertin/28d6bf1d9d1033ef926e20a1431df267 to your computer and use it in GitHub Desktop.
@receiver(post_delete, sender=Image)
def post_save_image(sender, instance, *args, **kwargs):
""" Clean Old Image file """
try:
instance.img.delete(save=False)
except:
pass
@receiver(pre_save, sender=Image)
def pre_save_image(sender, instance, *args, **kwargs):
""" instance old image file will delete from os """
try:
old_img = instance.__class__.objects.get(id=instance.id).img.path
try:
new_img = instance.image.path
except:
new_img = None
if new_img != old_img:
import os
if os.path.exists(old_img):
os.remove(old_img)
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment