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.

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

Review this article
Sending
User Review
0 (0 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 me@matthiasomisore.com.

Be the first to comment

Leave a Reply

Your email address will not be published.


*