收到错误“此后端不支持绝对路径。”在S3中覆盖文件时

时间:2019-07-09 05:27:26

标签: python django

我正在尝试根据此博客文章实现裁剪和上传功能:

https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html

尝试保存裁剪的照片时出现错误:

“ NotImplementedError:此后端不支持绝对路径。”

forms.py

class LetterPictureModelForm(forms.ModelForm):
    picture = forms.ImageField(
        label='Picture',
        widget=ClearableFileInput(attrs={
            'class': 'form-control',
            'placeholder': 'Picture'
        })
    )
    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    width = forms.FloatField(widget=forms.HiddenInput())
    height = forms.FloatField(widget=forms.HiddenInput())

    class Meta:
        model = LetterPicture
        fields = ['picture', 'x', 'y', 'width', 'height', ]
        widgets = {
                'letter': forms.HiddenInput(),
                'slot': forms.HiddenInput()
        }

    def save(self):
        letter_picture = super(LetterPictureModelForm, self).save()
        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')
        image = Image.open(letter_picture.picture)
        cropped_image = image.crop((x, y, w + x, h + y))
        resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
        resized_image.save(letter_picture.picture.path)

        return letter_picture

settings.py

STATICFILES_STORAGE = 'custom_storages.StaticStorage'

custom_storages.py

from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage

class StaticStorage(S3Boto3Storage):
    location = settings.STATICFILES_LOCATION


class MediaStorage(S3Boto3Storage):
    location = settings.MEDIAFILES_LOCATION

您可以看到,我正在使用S3保存媒体文件,到目前为止,该文件已经按预期工作了。

谁能告诉我是什么导致了此错误?我不明白这是什么意思。

更新

根据佐罗·詹的建议,我采用了此处使用的方法: Resize thumbnails django Heroku, 'backend doesn't support absolute paths'

def save(self):
    letter_picture = super(LetterPictureModelForm, self).save()
    x = self.cleaned_data.get('x')
    y = self.cleaned_data.get('y')
    w = self.cleaned_data.get('width')
    h = self.cleaned_data.get('height')

    image = Image.open(letter_picture.picture)
    cropped_image = image.crop((x, y, w + x, h + y))
    resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
    fh = storage.open(letter_picture.picture.name, "w")
    format = 'JPEG'  # You need to set the correct image format here
    resized_image.save(fh, format)
    fh.close()

    return letter_picture

我感觉到我犯了一个小错误,因为图像在S3中显示不变,没有抛出错误,但是我仍然找不到错误。

0 个答案:

没有答案