2

目的: テンプレートを使用して、生成された .png 画像を表示したいと考えています。

ここの例で作業しました。その例の最後のコード スニペットを次に示します。

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 のもの) を追加できます。

ここで関連するソリューションを見つけました。そのソリューションでは、次のようなことをお勧めします。

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ため、エラーが発生しました。responsec

画像を作成し、それをテンプレートに渡してレンダリングする正しい方法は何ですか?

4

1 に答える 1

3

画像をpngとして作成する作業ビューが既にあるので、gen_chart単に追加しないのはなぜですか

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

HTMLテンプレートに追加して、通常どおりレンダリングしますか? あなたはあなたの人生を困難にしようとしていますか?

于 2014-01-07T21:00:11.040 に答える