在django中删除缩略图

时间:2013-12-09 14:37:24

标签: django django-models thumbnails

当我上传管理界面的图片时,我也会创建图片的缩小版(缩略图)版本。 当我从管理界面删除图像时,我想要删除图像的小版本。怎么会实现这个目标?

models.py

from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from PIL import Image
import sys
class Picture(models.Model):
    filepath = 'thumbnails/'
    image = models.ImageField(verbose_name="Bild", upload_to='photos', max_length=255, blank=False)
    image_number = models.PositiveSmallIntegerField(verbose_name="Reihenfolge", null=True, blank=False)
    def save(self):
        sizes = {'thumbnail': {'height': 50, 'width': 50}}

        super(Picture, self).save()
        photopath = str(self.image.path)  # this returns the full system path to the original file
        im = Image.open(photopath)  # open the image using PIL

    # pull a few variables out of that full path
        extension = photopath.rsplit('.', 1)[1]  # the file extension
        filename = photopath.rsplit('\\', 1)[1].rsplit('.', 1)[0]  # the file name only (minus path or extension)
        fullpath = photopath.rsplit('\\', 1)[0]  # the path only (minus the filename.extension)

        # use the file extension to determine if the image is valid before proceeding
        if extension not in ['jpg', 'jpeg', 'gif', 'png']: sys.exit()

        # create thumbnail
        im.thumbnail((sizes['thumbnail']['width'], sizes['thumbnail']['height']), Image.ANTIALIAS)
        thumbname = filename + "_thumbnail.jpg"
        im.save(fullpath + '/' + thumbname)
        self.photo_thumb = self.filepath + thumbname

        super(Picture, self).save()

    def image_thumb(self, fixed_height=80):
        def html(url, height, width):
            return u'<img src="%s" height="%spx" width="%spx"/>' % (url, height, width)

        try:
            aspect_ratio = float(self.image.width) / self.image.height
            calculated_width = aspect_ratio * fixed_height
            return html(self.image.url, fixed_height, calculated_width)
        except IOError:
            return html('asd', fixed_height, fixed_height)

    image_thumb.short_description = 'Vorschau'
    image_thumb.allow_tags = True
    class Meta:
        verbose_name = "Bild"
        verbose_name_plural = "Bilder"

@receiver(pre_delete, sender=Picture)
def image_delete(sender, instance, **kwargs):
    instance.image.delete(False)

0 个答案:

没有答案