Resize thumbnails django Heroku, 'backend doesn't support absolute paths'

拜拜、爱过 提交于 2019-12-07 03:26:51

问题


I've got an app deployed on Heroku using Django, and so far it seems to be working but I'm having a problem uploading new thumbnails. I have installed Pillow to allow me to resize images when they're uploaded and save the resized thumbnail, not the original image. However, every time I upload, I get the following error: "This backend doesn't support absolute paths." When I reload the page, the new image is there, but it is not resized. I am using Amazon AWS to store the images.

I'm suspecting it has something to do with my models.py. Here is my resize code:

class Projects(models.Model):
    project_thumbnail = models.FileField(upload_to=get_upload_file_name, null=True, blank=True)

    def __unicode__(self):
        return self.project_name

    def save(self):
        if not self.id and not self.project_description:
            return

        super(Projects, self).save()
        if self.project_thumbnail:
            image = Image.open(self.project_thumbnail)
            (width, height) = image.size

        image.thumbnail((200,200), Image.ANTIALIAS)
            image.save(self.project_thumbnail.path)

Is there something that I'm missing? Do I need to tell it something else?


回答1:


Working with Heroku and AWS, you just need to change the method of FileField/ImageField 'path' to 'name'. So in your case it would be:

image.save(self.project_thumbnail.name)

instead of

image.save(self.project_thumbnail.path)



回答2:


I found the answer with the help of others googling as well, since my searches didn't pull the answers I wanted. It was a problem with Pillow and how it uses absolute paths to save, so I switched to using the storages module as a temp save space and it's working now. Here's the code:

from django.core.files.storage import default_storage as storage

...

   def save(self):
        if not self.id and not self.project_description:
            return

        super(Projects, self).save()
        if self.project_thumbnail:
            size = 200, 200
            image = Image.open(self.project_thumbnail)
            image.thumbnail(size, Image.ANTIALIAS)
            fh = storage.open(self.project_thumbnail.name, "w")
            format = 'png'  # You need to set the correct image format here
            image.save(fh, format)
            fh.close()


来源:https://stackoverflow.com/questions/18215989/resize-thumbnails-django-heroku-backend-doesnt-support-absolute-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!