AIM
I am attempting to:
- Create a histogram,
- Store it temporary memory,
- Pass the image to the template.
I am having trouble with Step 3 above. I suspect that I am making a simple and fundamental error in relation to passing the context
data to the template.
ERROR
HTML is rendering with a broken image tag.
CODE
Views.py
class SearchResultsView(DetailView):
...
def get(self, request, *args, **kwargs):
self.get_histogram(request)
return super(SearchResultsView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(SearchResultsView, self).get_context_data(**kwargs)
return context
def get_histogram(self, request):
""" Function to create and save histogram of Hashtag.locations """
# create the histogram
plt.show()
img_in_memory = BytesIO()
plt.savefig(img_in_memory, format="png")
image = base64.b64encode(img_in_memory.getvalue())
context = {'image':image}
return context
Results.html
<img src="data:image/png;base64,{{image}}" alt="Location Histogram" />
SOLUTION
In addition to issues with get
and get_context_data
as outlined by @ruddra below, another issue was that I had to decode the base64 string as a Unicode string. For more information, see here.
To do so, I included: image = image.decode('utf8')
So that, views.py looks like this:
def get_histogram(self, request):
# draw histogram
plt.show()
img_in_memory = BytesIO()
plt.savefig(img_in_memory, format="png") # save the image in memory using BytesIO
img_in_memory.seek(0) # rewind to beginning of file
image = base64.b64encode(img_in_memory.getvalue()) # load the bytes in the context as base64
image = image.decode('utf8')
return {'image':image}
You are calling the
get_histogram
in wrong way. You can do it like this:You don't need to call the
get_histogram
method inget
, or override theget
method.Update
I have tried like this:
Output looks like this: