Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Getting PIL Image save method to work with Amazon s3boto Storage

In order to resize images upon upload (using PIL), I'm overriding the save method for my Article model like so:

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 doesn't support absolute paths.

I tried replacing the image.save line with

image.save(self.image.url)

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

That is the correct location of the image though. If I put that address in the browser, the image is there. I tried a number of other things but so far, no luck.

like image 727
KrisF Avatar asked Feb 04 '13 04:02

KrisF


1 Answers

You should try and avoid saving to absolute paths; there is a File Storage API which abstracts these types of operations for you.

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

I'm not in an environment where I can test this code, but I believe you would 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()
like image 121
minism Avatar answered Sep 22 '22 15:09

minism