当我从数据库/模型中删除对象时,如何让Django Admin删除文件? [英] How do I get Django Admin to delete files when I remove an object from the database/model?

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

问题描述

我使用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_delete信号并在FileField对象上调用delete方法,因此(在models.py中):

You can receive the pre_delete signal 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 Admin删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆