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

时间:2015-01-05 00:10:01

标签: django-models

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

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(),倒数第二行。

1 个答案:

答案 0 :(得分:1)

您想要保存照片,因此您需要将某些内容分配给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)