【问题标题】:How to upload image as base64 in django-rest? i converted but. image still saves as regular image如何在 django-rest 中将图像上传为 base64?我转换了,但是。图像仍保存为常规图像
【发布时间】:2019-01-23 00:43:08
【问题描述】:

所以我在这里尝试转换它,然后传递给发布请求。 虽然我可以发送图像并且图像正在被转换,但它不会保存到数据库或发送到 API 中的字符串

def create(self, validated_data):
        #image_to_encode = validated_data['image']
        #encoded_string = base64.b64encode(image_to_encode.read() )
        #print(encoded_string)
        return Evento.objects.create(**validated_data)

这是我的序列化程序的一部分

【问题讨论】:

    标签: python django rest api django-rest-framework


    【解决方案1】:

    当您将图像编码为字符串时,您需要在经过验证的数据上以适当的字段名称设置该字符串,即

    def create(self, validated_data):
            image_to_encode = validated_data['image']
            encoded_string = base64.b64encode(image_to_encode.read() )
            validated_data['encoded_image'] = encoded_string
            return Evento.objects.create(**validated_data)
    

    【讨论】:

    • AttributeError: 'bytes' 对象没有属性 '_committed'
    • 这个错误可能是因为模型上的字段是models.ImageField,如果你想将图像存储为编码字符串你应该使用models.CharFieldmodels.TextField。请注意,我在编码图像文本的答案中使用了不同的字段(“encoded_image”)。
    • 我决定不使用base64,仍然得到同样的错误。但是,我设法使用其余文档来提供文件
    猜你喜欢
    • 2013-12-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2014-11-03
    相关资源
    最近更新 更多