问题
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}
回答1:
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:
来源:https://stackoverflow.com/questions/53127869/how-to-create-an-bytesio-img-and-pass-to-template