Home > Software design >  Django dynamically created temporary image not displaying
Django dynamically created temporary image not displaying

Time:11-18

I want to dynamically create an image based on user inputs and display this to the user.

views.py:

class TreatmentTemplateView(TemplateView):
    template_name = "../templates/patient/treatment_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["patient_id"] = self.kwargs["patient_id"]
        result = find_treatment(context["patient_id"])
        context = result[0]
        context["patient"] = result[1]
        context['image'] = result[2]
        print(context['image'])
        return context

It is at find_treatment(context["patient_id”]) that the image is generated by subfunction of find_treatment

fig = sns_plot.get_figure()
img_in_memory = BytesIO()
fig.savefig(img_in_memory, format="png") #dunno if your library can do that.
image = base64.b64encode(img_in_memory.getvalue())

And the template contains:

<img src="data:image/png;base64,{{image}}" />

The image is not displaying however, is this an issue with how i am referencing the image in the template?

CodePudding user response:

base64.b64encode probably returns a byte string. To convert as string you can use the DEFAULT_CHARSET defined in the django settings file or 'UTF-8'.

from django.conf import settings


image = image.decode(settings.DEFAULT_CHARSET)
  • Related