【发布时间】:2020-05-13 03:31:19
【问题描述】:
在 Django 视图中,我可以生成动态图像(PNG 格式的图形),它会创建一个响应,即我的图形图像。我可以让它显示在浏览器中,但没有网页 - 它只是图像。 现在我想将此图像嵌入到 HTML 模板中并呈现它。我怎样才能做到这一点? (这是我的第一个 Django 项目。)
import matplotlib.pyplot as plt
import numpy as np
import io
# Initialize the matplotlib figure
f, ax = plt.subplots(figsize=(6, 15))
width = my_data['bar_length']
data_names = my_data['ObjectNames']
y_pos = np.arange(len(data_names))
norm = plt.Normalize(my_data['bar_length'].min(), my_data['bar_length'].max())
cmap = plt.get_cmap("RdYlGn")
# Create horizontal bars
plt.barh(y_pos, width, color=cmap(norm(my_data['bar_length'].values)))
# Create names on the y-axis
plt.yticks(y_pos, data_names)
FigureCanvasAgg(f)
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close(f)
response = HttpResponse(buf.getvalue(), content_type='image/png')
# This works, but it generates just an image (no web page)
return response
# This ends up displaying the bytes of the image as text
#return render(request, 'my_app/graph.html', {'graph1': buf.getvalue()})
# This is what is in the graph.html template
# <div class="graph1">
# {{graph1 | safe}}
# </div>
【问题讨论】:
标签: django python-3.x matplotlib