通过覆盖保存方法在 Django 中调整图像大小

Resizing image in Django by overriding save method

我特别尝试在上传过程中按最大宽度调整图像大小,同时保持原始比例。我正在尝试通过拼凑其他示例来编写自己的保存方法,但我有一个问题。

class Mymodel(models.Model):
    #blablabla
    photo = models.ImageField(upload_to="...", blank=True)

    def save(self, *args, **kwargs):
        if self.photo:
            basewidth = 300
            filename = self.get_source_filename()
                    image = Image.open(filename)
            wpercent = (basewidth/float(image.size[0]))
            hsize = int((float(image.size[1])*float(wpercent)))
            img = image.resize((basewidth,hsize), PIL.Image.ANTIALIAS)
            self.photo.save()
        super(Mymodel, self).save(*args, **kwargs)

是 self.photo.save() 吗?或 img.save(),倒数第二行。

你想保存照片,所以你需要给self.photo分配一些东西,这是一个字段,所以它没有保存方法。您需要重新分配 self.photo,然后保存整个模型。

我想这就是你想要的:

def save(self, *args, **kwargs):
    # Did we have to resize the image?
    # We pop it to remove from kwargs when we pass these along
    image_resized = kwargs.pop('image_resized',False)

    if self.photo and image_resized:
        basewidth = 300
        filename = self.get_source_filename()
                image = Image.open(filename)
        wpercent = (basewidth/float(image.size[0]))
        hsize = int((float(image.size[1])*float(wpercent)))
        img = image.resize((basewidth,hsize), PIL.Image.ANTIALIAS)
        self.photo = img
        # Save the updated photo, but inform when we do that we
        # have resized so we don't try and do it again.
        self.save(image_resized = True)

    super(Mymodel, self).save(*args, **kwargs)