0

I have a user profile page with profile picture based on ImageField in my model. When I submit the form and upload a new image the original image file isn't deleted from /static/images/. How can I delete the old profile picture from images folder after new picture was uploaded?

Rares D
  • 113
  • 10
  • Are you overwriting the same file or creating a new file? – Moosa Saadat Jun 29 '20 at 07:51
  • Now when I upload a new foto it's creating a new file. I want to delete the old file after the new one was uploaded. – Rares D Jun 29 '20 at 07:59
  • An easier way is to **overwrite the same file**. So, it will be automatically deleted. But, for the other method, please share your code so that anyone can help. – Moosa Saadat Jun 29 '20 at 08:02
  • ok, so overwrite the same file sounds good, but how cand I do this? What part of code you want to see? – Rares D Jun 29 '20 at 08:13

1 Answers1

3

You can use pre_save signal to delete old file before saving the new file

from django.db.models.signals import pre_save
import os

@receiver(pre_save, sender=ImageModel)
def delete_old_file(sender, instance, **kwargs):
    # on creation, signal callback won't be triggered 
    if instance._state.adding and not istance.pk:
        return False
    
    try:
        old_file = sender.objects.get(pk=instance.pk).file
    except sender.DoesNotExist:
        return False
    
    # comparing the new file with the old one
    file = instance.file
    if not old_file == file:
        if os.path.isfile(old_file.path):
            os.remove(old_file.path)
minglyu
  • 2,958
  • 2
  • 13
  • 32
  • It looks very good, but is efficient? – Rares D Jun 29 '20 at 08:17
  • Please explain me this part: if instance._state.adding and not istance.pk: return False what it does? – Rares D Jun 29 '20 at 08:21
  • @RaresD it is as efficient as normal python functions since signals runs synchronously – minglyu Jun 29 '20 at 08:21
  • @RaresD On object creation, instance does not have pk yet, so we use `not instance.pk` to detect if it is created or not. read more here https://stackoverflow.com/questions/3607573/django-pre-save-signal-check-if-instance-is-created-not-updated-does-kwargsc – minglyu Jun 29 '20 at 08:26
  • Thanks! Now I understand! – Rares D Jun 29 '20 at 08:29