从数据库/模型中删除对象时,如何让Django Admin删除文件?
我将1.2.5与标准ImageField一起使用,并使用内置的存储后端。文件上传正常,但是当我从管理员删除条目时,服务器上的实际文件不会删除。
回答:
你可以接收pre_delete
或post_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)
以上是 从数据库/模型中删除对象时,如何让Django Admin删除文件? 的全部内容, 来源链接: utcz.com/qa/425291.html