Django delete file when object is deleted

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.

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 – 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.

Review this article
User Review
5 (9 votes)

About Matthias 33 Articles
I am a Software Engineer from Houston, TX who love to write codes that brings great ideas to live. In my professional life, I have created software for different industries including Oil & Gas, Finance, Service Provider, Cloud Computing and Embedded Systems. When not writting codes, i enjoy travelling, good music and photography. You can reach me at


  1. Thanks ALOT my friend, you saved me few hours with this post. I’m sadly disappointed that noone commented here, this post is very-very helpful, and deserves some posts.

  2. Muchisimas gracias, encontré este post después de 30 minutos buscando exactamente lo que publicaste!! Es la solucion exacta de lo que necesitaba !

  3. Thank you Matthias! You solved my problem in no time. I realized django was leaving files behind, googled the problem, and found your solution. Up and running again in 15′, I wish it was always like this!

  4. Totally saved me. I am redeveloping my site from MVC to django. This helped a super duper double a lot. LOL . TY.

1 Trackback / Pingback

  1. Delete Files When Deleting Models in Django – Colin Michael Lucien Jonathan Nelson’s Blog

Leave a Reply

Your email address will not be published.