参考简书文章Python Django 调用post_delete() 做自定义删除
import os
from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.conf import settings
...
class Media_blog(models.Model):
title = models.CharField(max_length=50)
pub_date = models.DateField()
content = models.TextField()
source = models.CharField(max_length=300)
source_description = models.CharField(max_length=50,
null=True,
blank=True)
photo = models.ImageField(null=True,
blank=True,
upload_to='image',
max_length=200)
class Meta:
ordering = ('title',)
def __str__(self):
return self.title
## 添加监听器
@receiver(post_delete, sender=Media_blog)
def delete_upload_files(sender, instance, **kwargs):
files = getattr(instance, 'photo')
if not files:
return
fname = os.path.join(settings.MEDIA_ROOT, str(files))
if os.path.isfile(fname):
os.remove(fname)
来源:CSDN
作者:uxk0587
链接:https://blog.csdn.net/weixin_41660414/article/details/104114415