2014-01-07 34 views
1

目標:我想使用模板顯示生成的.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變量不存在。

創建圖像並將其傳遞給模板進行渲染的正確方法是什麼?

+0

將它保存到一個文件,並使用img標籤....或將您的view_chart網址作爲src在img標籤 –

回答

2

既然你已經有一個工作gen_chart查看創建圖像以PNG爲什麼不加

<img src='{% url "gen_chart" %}' /> 

到HTML模板,通常呈現呢?你是想讓你的生活變得困難嗎?

+0

這就等於瘋狂。這是我缺乏理解,我做錯了。我會給你一個鏡頭。 –

+0

如果你簡單的想到它很容易:你的''gen_chart''視圖實際上是一個圖像。所以如果你把它包含到* any * html(不只是django模板),它會顯示該圖像! – Serafeim

+0

非常好,工作。感謝您的解釋,這絕對有助於理解這個概念。 –