django admin删除记录的同时删除文件

醉酒当歌 提交于 2020-01-30 15:48:50

参考简书文章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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!