为了账号安全,请及时绑定邮箱和手机立即绑定

删除博客文章后从媒体文件夹中删除图像

删除博客文章后从媒体文件夹中删除图像

波斯汪 2021-12-26 15:42:32
当我从我的 Django 博客中删除帖子时,该帖子已成功删除,但与该帖子关联的所有图像仍保留在我的media文件夹中。我如何确保这些也被删除?这是我的文件:模型.pyclass News(models.Model):    title = models.CharField(max_length=255)    body = models.TextField()    date = models.DateTimeField(auto_now_add=True)    author = models.ForeignKey(        get_user_model(),        on_delete=models.CASCADE,    )    thumb = models.ImageField(blank=True, null=True)    def __str__(self):        return self.title    def get_absolute_url(self):        return reverse('news_detail', args=[str(self.id)])视图.pyclass NewsDeleteView(LoginRequiredMixin, DeleteView):    model = News    template_name = 'news_delete.html'    success_url = reverse_lazy('news_list')    login_url = 'login'    def test_func(self):        obj = self.get_object()        return obj.author == self.request.usernews_delete.html{% extends 'base.html' %}{% block content %}    <h1>Delete</h1>    <form action="" method="post">{% csrf_token %}      <p>Are you sure you want to delete "{{ news.title }}"?</p>      <button class="btn btn-danger ml-2" type="submit">Confirm</button>    </form>{% endblock content %}
查看完整描述

2 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

在post_delete信号处理程序中最容易做到这一点:


from django.core.files.storage import default_storage


@receiver(post_delete, sender=News)

def delete_associated_files(sender, instance, **kwargs):

    """Remove all files of an image after deletion."""

    path = instance.thumb.name

    if path:

        default_storage.delete(path)

您还可以在包含文件字段的所有模型中使用 mixin 类:


from django.db.models.signals import post_delete


class FileDeletionMixin(object):

    file_fields = []  # list the names of the file fields


    def __init__(self, *args, **kwargs):

        super().__init__(*args, **kwargs)

        post_delete.connect(delete_associated_files, sender=self.__class__,

                            dispatch_uid=f"_file_deletion_mixin_{self._meta.model_name}-{self._meta.app_label}")


def delete_associated_files(sender, instance, **kwargs):

    """Remove all files of an image after deletion."""

    # you may want to add checks to be sure file_fields exists

    # e.g. if isinstance(instance, FileDeletionMixin)

    for field in instance.file_fields:  

        file = getattr(instance, field)  # you may want to catch exception AttributeError here

        if file:

            file.delete(save=False)


class News(FileDeletionMixin, models.Model):

    thumb = FileField # or ImageField

    file_fields = ['thumb']


查看完整回答
反对 回复 2021-12-26
?
catspeake

TA贡献1111条经验 获得超0个赞

在Django的清理包添加此功能FieldField和ImageField。


您可以使用安装它,pip install django-cleanup然后将其添加到settings.py:


INSTALLED_APPS = [

    ...

    'django_cleanup',

    ...

]


查看完整回答
反对 回复 2021-12-26
  • 2 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信