目標:我想使用模板顯示生成的.png圖像。Django:如何使用模板渲染圖像
我與示例here一起工作。下面是代碼從例如最後段:
def gen_chart(request):
...
pp = CairoPlot.PiePlot(surface, data, heigth, width, background = None, gradient = True, shadow = True, series_colors = colors)
pp.render()
response = HttpResponse(mimetype="image/png")
pp.surface.write_to_png(response)
return response
訪問gen_chart
視圖顯示了一個相當餅圖。但是,我想使用模板進行渲染,因此我可以在生成的頁面(標籤,說明,標題和其他html內容)中添加更多數據。
我找到了一個相關的解決方案here。在該解決方案中,建議做這樣的事情:
c = RequestContext(request,{'result':json.dumps(result)})
t = Template("{{result}}") # A dummy template
response = HttpResponse(t.render(c), mimetype = u'application/json')
return response
我嘗試如下,以適應代碼:
c = RequestContext(request, {'result': pp.surface.write_to_png(response)})
t = Template('test_app/pie_chart_template.html')
response = HttpResponse(t.render(c), mimetype="image/png")
return response
但正如你可能已經猜到了,我遇到了錯誤UnboundLocalError: local variable 'response' referenced before assignment
,因爲在創建c
時,response
變量不存在。
創建圖像並將其傳遞給模板進行渲染的正確方法是什麼?
將它保存到一個文件,並使用img標籤....或將您的view_chart網址作爲src在img標籤 –