Search code examples
pythondjangoimagefield

How to delete old profile picture when upload a new one - Django


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?


Solution

  • 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)