使用 pre_save 信号存储缩略图时出现 IOError

发布于 2024-09-14 03:26:28 字数 1041 浏览 7 评论 0原文

我有一个带有选项照片字段的模型。添加照片时,我希望自动创建并存储缩略图。但是,当我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙厌世 2024-09-21 03:26:28

我想通了。我遇到的问题是尝试保存缩略图字段,并且我试图在信号内执行此操作。因此,为了解决这个问题,我将缩略图字段保存在模型 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 :/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文