Django - Getting PIL image save method for working with Amazon s3boto storage

To resize images on upload (using PIL), I override the save method for my article model as follows:

def save(self): super(Article, self).save() if self.image: size = (160, 160) image = Image.open(self.image) image.thumbnail(size, Image.ANTIALIAS) image.save(self.image.path) 

This works locally, but in production I get an error: NotImplementedError: this backend does not support absolute paths.

I tried replacing the line image.save with

 image.save(self.image.url) 

but then I get IOError: [Errno 2] There is no such file or directory: ' https://my_bucket_name.s3.amazonaws.com/article/article_images/2.jpg '

This is the correct image location. If I placed this address in the browser, the image will be there. I have tried many other things, but still no luck.

+6
source share
1 answer

You should try to avoid maintaining absolute paths; There is a file storage API that abstracts these types of operations for you.

Looking at the PIL Documentation , it seems that the save() function supports passing a file object instead of a path.

I am not in an environment where I can check this code, but I believe that you need to do something like this instead of your last line:

 from django.core.files.storage import default_storage as storage fh = storage.open(self.image.name, "w") format = 'png' # You need to set the correct image format here image.save(fh, format) fh.close() 
+8
source

All Articles