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

当我从我的 Django 博客中删除帖子时,该帖子已成功删除,但与该帖子关联的所有图像仍保留在我的media文件夹中。我如何确保这些也被删除?


这是我的文件:


模型.py


class 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)])

视图.py


class 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.user

news_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 %}


波斯汪
浏览 156回答 2
2回答

喵喵时光机

在post_delete信号处理程序中最容易做到这一点:from django.core.files.storage import default_storage@receiver(post_delete, sender=News)def delete_associated_files(sender, instance, **kwargs):&nbsp; &nbsp; """Remove all files of an image after deletion."""&nbsp; &nbsp; path = instance.thumb.name&nbsp; &nbsp; if path:&nbsp; &nbsp; &nbsp; &nbsp; default_storage.delete(path)您还可以在包含文件字段的所有模型中使用 mixin 类:from django.db.models.signals import post_deleteclass FileDeletionMixin(object):&nbsp; &nbsp; file_fields = []&nbsp; # list the names of the file fields&nbsp; &nbsp; def __init__(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; super().__init__(*args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; post_delete.connect(delete_associated_files, sender=self.__class__,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dispatch_uid=f"_file_deletion_mixin_{self._meta.model_name}-{self._meta.app_label}")def delete_associated_files(sender, instance, **kwargs):&nbsp; &nbsp; """Remove all files of an image after deletion."""&nbsp; &nbsp; # you may want to add checks to be sure file_fields exists&nbsp; &nbsp; # e.g. if isinstance(instance, FileDeletionMixin)&nbsp; &nbsp; for field in instance.file_fields:&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; file = getattr(instance, field)&nbsp; # you may want to catch exception AttributeError here&nbsp; &nbsp; &nbsp; &nbsp; if file:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file.delete(save=False)class News(FileDeletionMixin, models.Model):&nbsp; &nbsp; thumb = FileField # or ImageField&nbsp; &nbsp; file_fields = ['thumb']

catspeake

在Django的清理包添加此功能FieldField和ImageField。您可以使用安装它,pip install django-cleanup然后将其添加到settings.py:INSTALLED_APPS = [&nbsp; &nbsp; ...&nbsp; &nbsp; 'django_cleanup',&nbsp; &nbsp; ...]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python