小编典典

从数据库/模型中删除对象时,如何让Django Admin删除文件?

django

我将1.2.5与标准ImageField一起使用,并使用内置的存储后端。文件上传正常,但是当我从管理员删除条目时,服务器上的实际文件不会删除。


阅读 761

收藏
2020-03-26

共1个答案

小编典典

你可以接收pre_deletepost_delete信号(请参见下面的@toto_tico的注释),并在FileField对象上调用delete()方法,因此(在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)
2020-03-26