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.