Purpose: I would like to display the generated .png image using the template.
I worked with an example here . Here is the final code snippet from this 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 shows a pretty pie chart. However, I would like to do this with a template, so I can add more data to the resulting page (labels, description, headers and other html materials).
I found the appropriate solution here . In this solution, he recommends doing 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 this 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 might have guessed, I ran into the UnboundLocalError: local variable 'response' referenced before assignment error UnboundLocalError: local variable 'response' referenced before assignment , since the response variable does not exist when creating c .
What is the correct way to create an image and pass it to a template for rendering?