I have an eCommerce application https://bdimart.com. 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 """ try: instance.img.delete(save=False) except: pass
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 """ 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
Make Getting file in django use try and except, because when file is mising or previously not upload, it will be error.