If you know the BASE_URL
in which you will save the images as when you deploy you could save then on an external bucket (storage) then you can make something like this:
class YourModelSerialiser(serializers.ModelSerializer):
image_url = serializers.SerializerMethodField()
class Meta:
model = YourModel
fields = ('some_field', 'some_other_field', 'image_url')
@staticmethod
def get_image_url(obj):
return BASE_URL + obj.image.url
but there is another approach you can use when you don't know or you don't care about the bucket(storage) url where image is saved:
class YourModelSerialiser(serializers.ModelSerializer):
image_encoded= serializers.SerializerMethodField()
class Meta:
model = YourModel
fields = ('some_field', 'some_other_field', 'image_encoded')
@staticmethod
def get_image_encoded(obj):
return base64.b64encode(obj.image)
for this one you have to import base64
and then in your front end you can load image as base64 like this
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Alt text" />
Ps. In the first example obj.image.url
is the path of the image in the bucket (let it be whatever), but you need the full path to load it on the front end side.