【发布时间】:2019-04-07 05:55:40
【问题描述】:
目标
我正在尝试:
- 创建直方图,
- 暂时存储它,
- 将图像传递给模板。
我在执行上述第 3 步时遇到问题。我怀疑我在将context 数据传递给模板时犯了一个简单而根本的错误。
错误
HTML 正在呈现带有损坏的图像标签。
代码
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" />
解决方案
除了下面@ruddra 概述的get 和get_context_data 的问题之外,另一个问题是我必须将base64 字符串解码为Unicode 字符串。如需更多信息,请参阅here。
为此,我添加了:image = image.decode('utf8')
所以,views.py 看起来像这样:
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}
【问题讨论】:
标签: django django-templates django-views bytesio