我试图通过将图像转换为base64并将其保存到postgresql中的'bytea'字段来在django中保存图像。我设法做到了,但字符串是用 UTF8 编码的。有没有一种方法可以仅针对该字段编码为 ascii?
这是我的自定义 Base64 模型字段的代码:
import base64
from django.db import models
class Base64Field(models.TextField):
def contribute_to_class(self, cls, name):
if self.db_column is None:
self.db_column = name
self.field_name = name + '_base64'
super(Base64Field, self).contribute_to_class(cls, self.field_name)
setattr(cls, name, property(self.get_data, self.set_data))
def get_data(self, obj):
#return obj.data_base64 #this works if the image is ascii-encoded
return base64.b64decode(getattr(obj, self.field_name)) #this also works well with the setter below
def set_data(self, obj, data):
setattr(obj, self.field_name, base64.encodestring(data)) #is encoded to UTF8
def db_type(self, connection):
return 'longtext'