1

I'm unable to save the image that is either being resized or uploading directly through my admin panel. I want to resize it through PLP or any other way!

def get_product_image_folder(instance, filename):

return "static/images/product/%s/base/%s" %(instance.product_id, filename)
product_image  = StringIO.StringIO(i.read())
imageImage = Image.open(product_image)

thumbImage = imageImage.resize((100,100))

thumbfile = StringIO()
thumbImage.save(thumbfile, "JPEG")

thumbcontent = ContentFile(thumbfile.getvalue())

newphoto.thumb.save(filename, thumbcontent)
new_photo.save()
Ganapathy
  • 545
  • 1
  • 6
  • 23
vartika
  • 11
  • 1

1 Answers1

0

This can be done either in the save method of the model, the save_model method of the admin, or the save method of the form.

I recommend the last one, since it lets you decouple form/validation logic from the model and admin interface.

This could look something like the following:

class MyForm(forms.ModelForm):
    model = MyModel

    ...
    def save(self, *args, **options):
        if self.cleaned_data.get("image_field"):
            image = self.cleaned_data['image_field']
            image = self.resize_image(image)
            self.cleaned_data['image_field'] = image
        super(MyForm, self).save(*args, **options)

    def resize_image(self, image):
        filepath = image.file.path
        pil_image = PIL.Image.open(filepath)
        resized_image = # **similar steps to what you have in your question
        return resized_image

You can either put this new image in the cleaned_data dictionary so that it saves itself, or you can save it to a new field (something like "my_field_thumbnail") that has editable=False on the model.

More info on the actual process of resizing an image with PIL can be found in other SO questions, eg: How do I resize an image using PIL and maintain its aspect ratio?

Community
  • 1
  • 1
Robert Townley
  • 3,414
  • 3
  • 28
  • 54