Search code examples
djangofilestoragedjango-modelsimagefield

How do I get Django Admin to delete files when I remove an object from the database/model?


I am using 1.2.5 with a standard ImageField and using the built-in storage backend. Files upload fine but when I remove an entry from admin the actual file on the server does not delete.


Solution

  • You can receive the pre_delete or post_delete signal (see @toto_tico's comment below) and call the delete() method on the FileField object, thus (in models.py):

    class MyModel(models.Model):
        file = models.FileField()
        ...
    
    # Receive the pre_delete signal and delete the file associated with the model instance.
    from django.db.models.signals import pre_delete
    from django.dispatch.dispatcher import receiver
    
    @receiver(pre_delete, sender=MyModel)
    def mymodel_delete(sender, instance, **kwargs):
        # Pass false so FileField doesn't save the model.
        instance.file.delete(False)