Reputation: 4412
Objective: I would like to display a generated .png image using a template.
I worked with the example here. Here is the final snippet of code from that example:
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
Accessing the gen_chart
view shows a pretty pie chart. However, I'd like to render this using a template, so I can add more data in the resulting page (Labels, description, headers, and other html stuff).
I found a related solution here. In that solution, it recommends to do something like this:
c = RequestContext(request,{'result':json.dumps(result)})
t = Template("{{result}}") # A dummy template
response = HttpResponse(t.render(c), mimetype = u'application/json')
return response
I tried to adapt that code as follows:
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
But as you may have guessed, I ran into the error UnboundLocalError: local variable 'response' referenced before assignment
, since the response
variable doesn't exist when creating c
.
What is the correct way to creating an image and pass it to a template to render?
Upvotes: 2
Views: 4690
Reputation: 15104
Since you already have a working gen_chart
view that creates your image as png why not just add a
<img src='{% url "gen_chart" %}' />
to your HTML template and render it normally ? You are you trying to make your life difficult ?
Upvotes: 3