2

我有一个带有选项照片字段的模型。添加照片后,我希望自动创建和存储缩略图。但是,当我使用 pre_save 信号执行此操作时,我不断收到 IOError,如果我尝试使用 post_save 信号执行此操作,我无法在不创建无限 post_save 循环的情况下将缩略图路径保存到我的模型。

这是代码

# using PIL 
from PIL import Image
import os
...

# my model
class Course(models.Model):
    ...
    photo = models.ImageField(upload_to='course_images/', blank=True, null=True)
    thumbnail = models.ImageField(upload_to='course_images/thumbnails/', blank=True, null=True, editable=False)
    ...

# my pre_save signal
def resize_image(sender, instance, *args, **kwargs):
    '''Creates a 125x125 thumbnail for the photo in instance.photo'''
    if instance.photo:
        image = Image.open(instance.photo.path)
        image.thumbnail((125, 125), Image.ANTIALIAS)
        (head, tail) = os.path.split(instance.photo.path)
        (a, b) = os.path.split(instance.photo.name)
        image.save(head + '/thumbnails/' + tail)
        instance.thumbnail = a + '/thumbnails/' + b

models.signals.pre_save.connect(resize_image, sender=Course)
4

1 回答 1

2

我想到了。我遇到的问题是试图保存缩略图字段,我试图在信号中做到这一点。因此,为了解决这个问题,我将缩略图字段保存在模型 save() 函数中,并留下信号以创建缩略图。

我花了一段时间才弄清楚:/

于 2010-08-13T20:26:02.920 回答