Delete PlaceImage files including thumbnails on deletion.
This commit is contained in:
		@@ -16,6 +16,7 @@ from django.db.models.signals import post_save
 | 
			
		||||
from django.dispatch import receiver
 | 
			
		||||
from django.core.validators import MaxValueValidator, MinValueValidator
 | 
			
		||||
from easy_thumbnails.fields import ThumbnailerImageField
 | 
			
		||||
from easy_thumbnails.files import get_thumbnailer
 | 
			
		||||
from taggit.managers import TaggableManager
 | 
			
		||||
 | 
			
		||||
# Create your models here.
 | 
			
		||||
@@ -177,18 +178,19 @@ class PlaceImage (Submittable):
 | 
			
		||||
 | 
			
		||||
        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)
 | 
			
		||||
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.
 | 
			
		||||
    """
 | 
			
		||||
    if instance.filename:
 | 
			
		||||
        if os.path.isfile(instance.filename.path):
 | 
			
		||||
            os.remove(instance.filename.path)
 | 
			
		||||
        # Get and delete all files and thumbnails from instance
 | 
			
		||||
        thumbmanager = get_thumbnailer(instance.filename)
 | 
			
		||||
        thumbmanager.delete(save=False)
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@receiver(models.signals.pre_save, sender=PlaceImage)
 | 
			
		||||
@@ -206,6 +208,7 @@ def auto_delete_file_on_change(sender, instance, **kwargs):
 | 
			
		||||
    except PlaceImage.DoesNotExist:
 | 
			
		||||
        return False
 | 
			
		||||
 | 
			
		||||
    # No need to delete thumbnails, as they will be overwritten on regeneration.
 | 
			
		||||
    new_file = instance.filename
 | 
			
		||||
    if not old_file == new_file:
 | 
			
		||||
        if os.path.isfile(old_file.path):
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user