我的 django View 如下。我正在使用 matplotlib 生成条形图。
def myview(request, pk, sub):
x=[1,2,3,4,5,6]
y=[5,2,6,8,2,7]
plot(x,y, linewidth=2)
xlabel('x-axis')
ylabel('yaxis')
title('sample graph')
grid(True)
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
graphIMG.save(buffer, "PNG")
pylab.close()
assgn = MyModel.objects.filter(data=pk, subject=sub)
return render_to_response('mypage.html', {'assgn':assgn})
如何在 render_to_response
中传递条形图和查询?另外我将如何在我的 html 中绘制这个图表?
最佳答案
您必须将绘图保存为图像文件,并将该文件的链接传递给您的模板。我不熟悉您使用的库,但我假设以下行会将图形保存到实际的 png 文件中:
graphIMG.save(buffer, "PNG")
将其保存到磁盘后,您应该有一个文件路径。确保 Django 可以访问此文件(即将文件放入 settings.py 文件中 MEDIA_ROOT 指定的文件夹中)。
现在,将图表的路径传递到模板:
from django.shortcuts import render
def myview(request, pk, sub):
...
imagepath = ...
context = {'imagepath': imagepath}
return render_to_response('mypage.html', context}
然后,在您的模板中:
<img src="{{ imagepath }}">
第一次尝试时您可能不会得到这个(即图像未显示)。要调试它,请打开网页并检查图像的链接,复制链接并将其粘贴到浏览器中以查看是否可以访问它。如果没有,请检查您的 urls.py 并添加以下行,以便 Django 提供图像文件:
urlpatterns = patterns('',
...,
url(r'^images/(.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
请注意 r'^images/(.*)$' 部分,您的设置可能与我的不同。
这里是文档:https://docs.djangoproject.com/en/1.4/howto/static-files/
该文档适用于 django 1.4(因此请单击您使用的版本),但它也适用于 django 的更高版本。该文档还提供了该解决方案的“快捷”版本。所以请阅读它。
正如文档中提到的,该解决方案仅适合开发。在生产中,您可能希望使用 apache 或 nginx 来提供静态内容。
关于python - 通过 django 中的 View 将 matplotlib 图形渲染为 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30066689/