Categories
Python Answers

How to get Python Django Admin to delete files when removing an object from the database/model?

Spread the love

To get Python Django Admin to delete files when I remove an object from the database/model, we can use the delete method.

For instance, we write

class MyModel(models.Model):
    file = models.FileField()
    #...

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):
    instance.file.delete(False)

to add the mymodel_delete function and we apply the receiver decorator on it.

We call receiver with pre_delete to run mymodel_delete before deleting the model entry.

In mymodel_delete, we call instance.file.delete with False to delete the file without saving to the model.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *