Как создать BytesIO img и перейти к шаблону
AIM
Я пытаюсь:
- Создать гистограмму,
- Сохраните это временную память,
- Передайте изображение в шаблон.
У меня проблемы с шагом 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" />
РЕШЕНИЕ
В дополнение к проблемам с get
а также get_context_data
как обрисовано в общих чертах @ruddra ниже, другая проблема заключалась в том, что мне пришлось декодировать строку base64 как строку Unicode. Для получения дополнительной информации см. Здесь.
Для этого я включил: 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}
1 ответ
Решение
Вы звоните get_histogram
неправильно Вы можете сделать это так:
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
Вам не нужно звонить get_histogram
метод в get
или переопределить get
метод.
Обновить
Я пытался так:
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