我在这个问题上度过了一天没有成功,所以我们将不胜感激。
我使用reportlab生成图表,并使用此tutorial成功将其呈现给浏览器:
d = MyBarChartDrawing()
#extract the request params of interest.
#I suggest having a default for everything.
if 'height' in request:
d.height = int(request['height'])
if 'width' in request:
d.width = int(request['width'])
if 'numbers' in request:
strNumbers = request['numbers']
numbers = map(int, strNumbers.split(','))
d.chart.data = [numbers] #bar charts take a list-of-lists for data
if 'title' in request:
d.title.text = request['title']
#get a GIF (or PNG, JPG, or whatever)
binaryStuff = d.asString('png')
return HttpResponse(binaryStuff, 'image/png')
我的问题是,我想在模板中渲染这个png,就像这样(不起作用):
return render(request, "subscription/monitorSizes.html", {'form':form,'message':'','graph':binaryStuff})
我多年来一直在讨论这个问题。这无疑是一个新手问题!为了挽救我的理智,我会很感激这方面的建议。非常感谢:))
编辑:我在同一个问题上找到了另一个stackoverflow Q,但它并没有真正解决。
答案 0 :(得分:3)
在views.py
中def show_image(request):
d = MyBarChartDrawing()
#extract the request params of interest.
#I suggest having a default for everything.
if 'height' in request:
d.height = int(request['height'])
if 'width' in request:
d.width = int(request['width'])
if 'numbers' in request:
strNumbers = request['numbers']
numbers = map(int, strNumbers.split(','))
d.chart.data = [numbers] #bar charts take a list-of-lists for data
if 'title' in request:
d.title.text = request['title']
#get a GIF (or PNG, JPG, or whatever)
binaryStuff = d.asString('png')
return HttpResponse(binaryStuff, 'image/png')
def somepage(request):
return render(request, "subscription/monitorSizes.html", {'form':form,'message':'','graph':reverse('show_image')})
在urls.py
...
url(r'^show_image/$', 'your_view.show_image', name='show_image'),
url(r'^somepage/$', 'your_view.somepage', name='somepage'),
...
在subscription / monitorSizes.html
中...
{% if graph != '' %} <img src="{{ graph }}" alt="some_text"> {% endif %}
...