[Django]-How to create an BytesIO img and pass to template

3👍

You are calling the get_histogram in wrong way. You can do it like this:

class SearchResultsView(DetailsView):
    ...

    def get_context_data(self, **kwargs):
         context = super(SearchResultsView, self).get_context_data(**kwargs)
         context.update(self.get_histogram(self.request))
         return context

You don’t need to call the get_histogram method in get, or override the get method.

Update

I have tried like this:

 class SearchResultsView(DetailsView):
     ...

     def get_histogram(self):
         x = 2
         y = 3
         z = 2
         t= 3    
         plt.plot(x, y)
         plt.plot(z, t)
         plt.show()
         img_in_memory = io.BytesIO()  # for Python 3
         plt.savefig(img_in_memory, format="png")
         image = base64.b64encode(img_in_memory.getvalue())
         return {'image':image}

     def get_context_data(self, *args, **kwargs):
         context = super(SearchResultsView, self).get_context_data(*args, **kwargs)
         context.update(self.get_histogram())
         return context

Output looks like this:
enter image description here

👤ruddra

Leave a comment