1

I currently have something like this

class Serializer_ListEmployee(ModelSerializer): user = Serializer_ListUser() class Meta: model = modelEmployee fields = [ 'user', 'employee_image', ] 

Any suggestions on how I can get back a base64 encoded string instead ?

2 Answers 2

4

If you only want the get the base64 from serializer then you can do something like this : [Edit as mentioned in another answer]

class EmployeeSerializer(serializers.ModelSerializer): employee_image = serializers.SerializerMethodField(read_only=True) class Meta: model = modelEmployee fields = [ 'user', 'employee_zip', 'employee_image', ] def get_employee_image(self, place): img = open( self.employee_image.path, "rb") data = img.read() return "data:image/jpg;base64,%s" % data.encode('base64') 

Reference : http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

But if you want two way, like read and write both then you can go with something like this :

from django.db import models class Photo( models.Model ): title = models.CharField( max_length=255 ) image = models.ImageField( upload_to="photos/", max_length=255) @property def image_url( self ): try: img = open( self.image.path, "rb") data = img.read() return "data:image/jpg;base64,%s" % data.encode('base64') except IOError: return self.image.url 

Source : http://www.codedependant.net/2012/04/13/increase-site-performance-with-django-base64-encod/

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

Comments

1

Create a serializer method for image field. In that field read the image from source and convert it base64 string.

Refer here http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield for creating a method field.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.