I'm trying to save an image in django by converting it to base64 and saving it to 'bytea' field in postgresql. I've managed to do it, but the string is encoded in UTF8. Is there a way I could encode to ascii just for this field?
Here's my code for a custom Base64 model field:
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'