Python 通过django中的视图将matplotlib图形呈现为html
我对django的看法如下。我正在使用matplotlib生成条形图Python 通过django中的视图将matplotlib图形呈现为html,python,django,matplotlib,Python,Django,Matplotlib,我对django的看法如下。我正在使用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()
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\u to\u 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 }}">
然后,在模板中:
from django.shortcuts import render
def myview(request, pk, sub):
...
imagepath = ...
context = {'imagepath': imagepath}
return render_to_response('mypage.html', context}
<img src="{{ imagepath }}">
请注意r“^images/(.*)$”部分,您的设置可能与我的不同
以下是文件:
该文档适用于django 1.4(因此请单击您使用的版本),但它也适用于django的更高版本。该文档还提供了此解决方案的“快捷方式”版本。那就读吧
如文档中所述,此解决方案仅适用于开发。在生产中,您可能希望使用apache或nginx来提供静态内容。@RogerFederer很高兴听到这个消息!你做了哪些小改动?