Ошибка при получении «Этот бэкэнд не поддерживает абсолютные пути». при перезаписи файла в S3 - PullRequest
0 голосов
/ 09 июля 2019

Я пытаюсь реализовать функцию обрезки и загрузки в соответствии с этой записью в блоге:

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 для сохранения медиа-файлов, которая до сих пор работала, как и ожидалось.

Может кто-нибудь сказать мне, что вызывает эту ошибку?Я не понимаю, что это значит.

Обновление

По предложению Зоро-Дзен я принял подход, который использовался здесь: Изменение размера эскизов djangoHeroku, «backend не поддерживает абсолютные пути»

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 отображаются без изменений, без ошибок, я могу »пока не могу найти мою ошибку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...