这似乎是一个老问题,并且有一段时间没有活动,但我最近遇到了类似的问题。我能够解决它,所以我想我可以分享我的解决方案。就这样吧。
在您的 html 模板中,您应该有一个按钮来触发 ajax 请求。例如:
***index.html***
<a href="#" id="plot">Plot</a>
<div id="imagediv"></div>
$('#plot').click(function(){
$.ajax({
"type" : "GET",
"url" : "/Plot/",
"data" : "str",
"cache" : false,
"success" : function(data) {
$('#imagediv').html(data);
}
});
});
你的views.py(或者一个单独的文件,例如:utils.py)应该有一个绘制图表的函数。
***utils.py***
@login_required()
def MatPlot(request):
# Example plot
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N)) ** 2
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
# The trick is here.
f = io.BytesIO()
plt.savefig(f, format="png", facecolor=(0.95, 0.95, 0.95))
encoded_img = base64.b64encode(f.getvalue()).decode('utf-8').replace('\n', '')
f.close()
# And here with the JsonResponse you catch in the ajax function in your html triggered by the click of a button
return JsonResponse('<img src="data:image/png;base64,%s" />' % encoded_img, safe=False)
当然你需要用一个url来连接这个函数,所以:
***urls.py***
url(r'^plot/$', Matplot, name='matplot')