简体   繁体   中英

remove images from media folder after deleting blog post

When I delete a post from my Django blog the post is successfully removed but any images associated with the post remain in my media folder. How do I ensure these are also deleted?

Here are my files:

models.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)])

views.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 %}

It's easiest to do this in the post_delete signal handler:

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)

You could also use a mixin class in all models containing file fields:

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']

The django-cleanup package adds this functionality to FieldField and ImageField .

You can install it using pip install django-cleanup then add this to settings.py :

INSTALLED_APPS = [
    ...
    'django_cleanup',
    ...
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM