I have a model that has an option photo field. When a photo is added, I want a thumbnail to be automatically created and stored. However, when I do this with a pre_save signal, I keep getting an IOError, and if I try to do it with a post_save signal I can't save the thumbnails path to my model without creating and infinite post_save loop.
我有一个模型有一个选项photo字段。当添加照片时,我希望自动创建并存储缩略图。但是,当我使用pre_save信号执行此操作时,我始终会得到一个IOError,如果我尝试使用post_save信号,我无法在不创建和无限post_save循环的情况下将缩略图路径保存到模型中。
Here's the code
这是代码
# 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)
1 个解决方案
#1
2
I figured it out. The problem I was having was trying to save the thumbnail field, and I was trying to do that within a signal. So to fix that I save the thumbnail field in the models save() function instead, and leave the signal to create the thumbnail.
我想出来。我遇到的问题是试图保存缩略图字段,我试图在一个信号中做到这一点。为此,我将缩略图字段保存在models save()函数中,并保留创建缩略图的信号。
Just took me awhile to figure out :/
我花了一段时间才明白:/。
#1
2
I figured it out. The problem I was having was trying to save the thumbnail field, and I was trying to do that within a signal. So to fix that I save the thumbnail field in the models save() function instead, and leave the signal to create the thumbnail.
我想出来。我遇到的问题是试图保存缩略图字段,我试图在一个信号中做到这一点。为此,我将缩略图字段保存在models save()函数中,并保留创建缩略图的信号。
Just took me awhile to figure out :/
我花了一段时间才明白:/。