Tech Incent

How to delete file when models instance is delete or update in Django?


I have an eCommerce application when we develop this application we face problems with files like image or pdf delete files from the application. The problem is: when we delete the model instance or update the model instance file field the file or old file not delete. because the Django system saves the old files also.

In our large e-commerce application, This is a huge problem with unused files in our application. because we don’t archive old unused files. So in this article, I share how to remove unused files with Django signal, when model instance deletes or update.

let’s Declare model example

class Image(models.Model):
    """ Default Image Model """
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
    name = models.CharField(max_length=200, blank=True, null=True)
    img = models.ImageField(upload_to='images')

    created_at = models.DateTimeField(auto_now_add=True)

when we delete Image instance, delete img file

@receiver(post_delete, sender=Image)
def post_save_image(sender, instance, *args, **kwargs):
    """ Clean Old Image file """

in default django, instance.img.delete(save=True) is responsible for save old file.  So post delete save=False can be responsible models instance file delete.

When update instance, delete old img file

Django pre_save can delete old image file. let’s see example:

@receiver(pre_save, sender=Image)
def pre_save_image(sender, instance, *args, **kwargs):
    """ instance old image file will delete from os """
        old_img = instance.__class__.objects.get(
            new_img = instance.image.path
            new_img = None
        if new_img != old_img:
            import os
            if os.path.exists(old_img):

Make Getting file in django use try and except, because when file is mising or previously not upload, it will be error.

Related posts

How to setup django static and media file in aws s3 ?

Sajal Mia

Explained Django inline formset factory with example?

Sajal Mia

How to deploy django and react in heroku ?

Tech Incent

How to work with django ajax requests ?

Sajal Mia

How to set up django react together ?

Sajal Mia

How to optimize your Django application for more speed with ORM?

Sajal Mia