2

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'

1 Answer 1

2

Either use a text field with base64-encoded text, or store the binary data in a bytea field. Don't store base64-encoded binary in a bytea field, that's just confusing.

I recommend using bytea and bytea_output = 'hex' (default in 9.0 and above).

Sign up to request clarification or add additional context in comments.

1 Comment

saving binary directly to bytea is a good idea indeed. this class helped me do it: github.com/niwibe/django-orm-extensions/blob/master/django_orm/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.