Answer the question
In order to leave comments, you need to log in
How to properly set post_save signal to delete an image?
There is a model with the img field (user photo)
class Profile(models.Model):
img = models.ImageField(upload_to=user_directory_path, verbose_name='Ваше фото')
def user_directory_path(instance, filename):
return 'images/{0}/{1}'.format(instance.name, filename)
@receiver(post_init, sender=Profile)
def backup_image_path(sender, instance, **kwargs):
if instance.img:
instance._current_imagen_file = instance.img
@receiver(post_save, sender=Profile)
def delete_old_image(sender, instance, **kwargs):
if hasattr(instance, '_current_imagen_file'):
if instance._current_imagen_file != instance.img.path:
instance._current_imagen_file.delete(save=False)
Answer the question
In order to leave comments, you need to log in
It's better to use pre_save to be able to compare the old and new value of the img field:
@receiver(pre_save, sender=Profile)
def my_handler(sender, instance, **kwargs):
if instance.pk:
old = Profile.objects.get(pk=instance.pk)
path = old.img.path
if path != instance.img.path:
os.remove(path)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question