By default, when objects containing file fields such as FileField or ImageField are deleted, Django does not delete the attached files, leaving you with a lot of orphaned files on your server.
By adding below codes to your model, Django will also delete attachments when the parent object is deleted.
#models.py from django.db.models.signals import post_delete from django.dispatch import receiver class MyModel(models.Model): """Model containing file field""" file = models.FileField(upload_to='somewhere', blank=False) ... @receiver(post_delete, sender=MyModel) def submission_delete(sender, instance, **kwargs): instance.file.delete(False)
* instance.file – ensures that only the current file is affected
* Passing “false” to instance.file.delete ensures that FileField does not save the model
* Unlike pre_delete, post_delete signal is sent at the end of a model’s delete() method and a queryset’s delete() method. This is safer as it does not execute unless the parent object is successfully deleted.