Skip to content

Instantly share code, notes, and snippets.

@xleon
Last active December 26, 2015 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xleon/7113771 to your computer and use it in GitHub Desktop.
Save xleon/7113771 to your computer and use it in GitHub Desktop.
When using easy_thumbnails on django you want to delete created thumbnails in two cases: 1) you update or "clean" the image file of the model 2) you delete the model instance. Using Signals, this is pretty easy This code is tested and working when updating one item, removing it and it also works when bulk deleting
from easy_thumbnails.models import Source, Thumbnail
from django.db import models
from django.db.models.signals import pre_delete, pre_save
from project_package import settings
class Project(models.Model):
name = models.CharField("Name", max_length=255)
main_image = models.ImageField("Main Image", blank=True, null=True, upload_to='uploads')
def __unicode__(self):
return self.name
def clean_thumbnails(self, delete_source=False):
if self.main_image:
sources = Source.objects.filter(name=self.main_image.name)
if sources.exists():
for thumb in Thumbnail.objects.filter(source=sources[0]):
try:
os.remove(os.path.join(settings.MEDIA_ROOT, thumb.name))
thumb.delete()
except Exception, e:
print "error " + e.message
if delete_source:
for source in sources:
source.delete()
""" Signals """
def pre_delete_project(sender, instance, *args, **kwargs):
instance.clean_thumbnails(True)
def pre_save_project(sender, instance, *args, **kwargs):
saved = sender.objects.filter(id=instance.id)
if saved.exists():
saved[0].clean_thumbnails()
pre_delete.connect(pre_delete_project, Project)
pre_save.connect(pre_save_project, Project)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment