'Django rest framework returning base64 image URL encoded

I have my viewset that returns a basse64 encoded image in the image variable:

with open(f"image_file.jpg" , "rb") as image_file:
            order.image = base64.encodebytes(image_file.read()).decode('utf-8')

The thing is, if this code is executed locally like python script.py it returns the right base64 and I can display it, but this viewset is returning a base64 that's URL encoded. Instead of returning something like NMR//9k=, it's returning NMR/9k%3D%0A.

How can I change this? I need the proper base64 encoding to display the image on the front.



Solution 1:[1]

I managed to solve this issue by creating a dict for the base64 images outside the serializer of the model, which was the one doing that URL encoding. I also had to remove new line characters as the response was drawing them as characters.

with open(f"image_file.jpg" , "rb") as image_file:
    images_dict["image_1"] = base64.encodebytes(image_file.read()).decode('utf-8').replace("\n", "")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barraguesh