Django 删除upload_to文件

新版Django在admin后台直接删除一条数据时,file = models.FileField(upload_to=‘file’)上传的文件并不会删除,以下为解决方法:

在model.py加入:

from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
@receiver(pre_delete, sender=AddDateModel)
def mymodel_delete(sender, instance, **kwargs):
    # Pass false so FileField doesn't save the model.
    instance.file.delete(False)

你可能感兴趣的:(Python,后端,Django)