问题
使用django自带admin后台删除表的时候 , 因为文件是存在服务器的 , 所以是只是删除了数据库的数据 , 而服务器的文件还存在
解决
models.py
# 模型类
class ProjectTable(models.Model):
# # 附件
enclosure = models.FileField(upload_to='project', verbose_name='附件', null=True, blank=True) # 附件
class Meta:
db_table = 'project'
verbose_name = '项目表'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
pass
import os
from django.dispatch import receiver
from django.db.models.signals import post_delete
from django.conf import settings
## 添加监听器
@receiver(post_delete, sender=模型类)
def delete_upload_files(sender, instance, **kwargs):
files = getattr(instance, '文件字段')
if not files:
return
fname = os.path.join(settings.MEDIA_ROOT, str(files))
if os.path.isfile(fname):
os.remove(fname)
pass
# 第二种
@receiver(pre_delete, sender=模型类)
def delete(sender, instance, **kwargs):
instance.文件字段.delete(False)
修改
#修改时
@receiver(post_init, sender=模型类名)
def file_path(sender, instance, **kwargs):
instance._current_file = instance.文件字段
@receiver(post_save, sender= Company)
def delete_old_image(sender, instance, **kwargs):
if hasattr(instance, '_current_file'):
if instance._current_file != instance.文件字段.path:
instance._current_file.delete(save=False)
注意bug
如果出现file没有关联文件,请将.path删除。
标签:sender,name,admin,django,instance,file,后台,delete From: https://www.cnblogs.com/superip/p/17263285.html