1

我在调整大小后将用户头像上传到 S3。我的 ModelForm 如下:

class UserAvatarForm(forms.ModelForm):
    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 = UserProfile
        fields = ('id', 'img', 'x', 'y', 'width', 'height')

    def save(self, *args, **kwargs):
        photo = super(UserAvatarForm, 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(photo.img)
        cropped_image = image.crop((x, y, w+x, h+y))
        resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
        resized_image.save(photo.img.path)

        return photo

NotImplementedError at /profile/avatar/ 此后端不支持绝对路径。

我已经看到我可以编辑 save 方法以使用File Storage API,但我不知道如何实现它。有什么帮助吗?谢谢

4

1 回答 1

2

这使它工作;我将把它留在这里以供将来参考:

def save(self, *args, **kwargs):
    photo = super(UserAvatarForm, 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(photo.img)
    cropped_image = image.crop((x, y, w+x, h+y))
    resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
    storage_path = storage.open(photo.img.name, "wb")
    resized_image.save(storage_path, 'png')
    storage_path.close()

    return photo
于 2017-07-18T13:38:55.380 回答