Delete PlaceImage files including thumbnails on deletion.

This commit is contained in:
Marcus Scholz 2020-09-18 13:40:54 +02:00
parent 21217b067f
commit 30b42de86f

View File

@ -16,6 +16,7 @@ from django.db.models.signals import post_save
from django.dispatch import receiver from django.dispatch import receiver
from django.core.validators import MaxValueValidator, MinValueValidator from django.core.validators import MaxValueValidator, MinValueValidator
from easy_thumbnails.fields import ThumbnailerImageField from easy_thumbnails.fields import ThumbnailerImageField
from easy_thumbnails.files import get_thumbnailer
from taggit.managers import TaggableManager from taggit.managers import TaggableManager
# Create your models here. # Create your models here.
@ -177,18 +178,19 @@ class PlaceImage (Submittable):
return ' '.join([self.place.name, str(self.pk)]) return ' '.join([self.place.name, str(self.pk)])
# These two auto-delete files from filesystem when they are unneeded:
# These two auto-delete files from filesystem when they are unneeded:
@receiver(models.signals.post_delete, sender=PlaceImage) @receiver(models.signals.post_delete, sender=PlaceImage)
def auto_delete_file_on_delete(sender, instance, **kwargs): def auto_delete_file_on_delete(sender, instance, **kwargs):
""" """
Deletes file from filesystem Deletes file (including thumbnails) from filesystem
when corresponding `PlaceImage` object is deleted. when corresponding `PlaceImage` object is deleted.
""" """
if instance.filename: if instance.filename:
if os.path.isfile(instance.filename.path): # Get and delete all files and thumbnails from instance
os.remove(instance.filename.path) thumbmanager = get_thumbnailer(instance.filename)
thumbmanager.delete(save=False)
@receiver(models.signals.pre_save, sender=PlaceImage) @receiver(models.signals.pre_save, sender=PlaceImage)
@ -206,6 +208,7 @@ def auto_delete_file_on_change(sender, instance, **kwargs):
except PlaceImage.DoesNotExist: except PlaceImage.DoesNotExist:
return False return False
# No need to delete thumbnails, as they will be overwritten on regeneration.
new_file = instance.filename new_file = instance.filename
if not old_file == new_file: if not old_file == new_file:
if os.path.isfile(old_file.path): if os.path.isfile(old_file.path):