stephan
stephan

Reputation: 2393

Resizing image in Django by overriding save method

I am specifically trying to resize an image during upload by max width while keeping the original ratio. I am trying to write my own save method by piecing together others examples but I have a question.

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)

is it self.photo.save() ? or img.save(), second to last line.

Upvotes: 2

Views: 846

Answers (1)

user764357
user764357

Reputation:

You want to save the photo, so you need to assign something to self.photo which is a field, so it won't have a save method. You need to reassign self.photo and then save the whole model.

I presume this is what you want:

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)

Upvotes: 1

Related Questions