使用 pre_save 信号存储缩略图时出现 IOError
我有一个带有选项照片字段的模型。添加照片时,我希望自动创建并存储缩略图。但是,当我使用 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)
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.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想通了。我遇到的问题是尝试保存缩略图字段,并且我试图在信号内执行此操作。因此,为了解决这个问题,我将缩略图字段保存在模型 save() 函数中,并留下信号来创建缩略图。
我花了一段时间才弄清楚:/
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.
Just took me awhile to figure out :/