本文介绍了当我从数据库/模型中删除对象时,如何让 Django 管理员删除文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

您可以接收 pre_deletepost_delete 信号(请参阅下面@toto_tico 的评论)并调用 pre_deletepost_delete 信号a href="https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.fields.files.FieldFile.delete" rel="noreferrer">delete() 方法,因此(在 models.py 中):

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)

这篇关于当我从数据库/模型中删除对象时,如何让 Django 管理员删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 22:35