Python 模型保存方法。保存前调整图像大小

Python 模型保存方法。保存前调整图像大小,python,django,django-models,python-imaging-library,Python,Django,Django Models,Python Imaging Library,我正在尝试在保存图像之前调整其大小。我在模型上使用自定义保存方法,但遇到了一个障碍 这是我现在拥有的代码: class UserImages(models.Model): height = models.CharField(blank=True, max_length=100) width = models.CharField(blank=True, max_length=100) image = models.ImageField(upload_to="UserImag

我正在尝试在保存图像之前调整其大小。我在模型上使用自定义保存方法,但遇到了一个障碍

这是我现在拥有的代码:

class UserImages(models.Model):
    height = models.CharField(blank=True, max_length=100)
    width = models.CharField(blank=True, max_length=100)
    image = models.ImageField(upload_to="UserImages/%Y/%m/%d", height_field='height', width_field='width')
    owner = models.ForeignKey(User)

    def __unicode__(self):
        return str(self.image)
    def save(self, *args, **kwargs):
        if self.image:
            filename = str(self.image.path)
            img = Image.open(filename)

            if img.mode not in ('L', 'RGB'):
                img = img.convert('RGB')

            img = ImageOps.fit(img, (180,240), Image.ANTIALIAS, 0, (0.5, 0.5))
            img.save(self.image.path)
        super(UserImages, self).save(*args, **kwargs)
此操作失败,并告诉我无法找到该文件。据我所知,这与图像目前只存在于内存中,因此无法像这样打开有关

所以我的问题是:我如何从内存中打开图像并将其保存回内存,以便默认的保存方法可以处理它


非常感谢您的帮助,这让我非常恼火:)

您需要保存您的
UserImages
,然后再尝试访问它的
ImageField

可在此代码段中找到如何执行此操作的示例:

基本上:

super(UserImages, self).save()
注:您的模型应该有一个单数名称,例如
UserImage
,而不是
UserImages

使用django resized

pip install django-resized
models.py

from django_resized import ResizedImageField

class MyModel(models.Model):
    ...
    image = ResizedImageField(max_width=500, max_height=300, upload_to='whatever')

有关更多信息,请查看

非常感谢。先想储蓄,但后来又忘了。不知道为什么。谢谢你的名字。我一直用复数来命名我所有的模型,这一个一定是通过了最后一个检查:)这似乎破坏了我的文件上传