Django: How to render image with a template

余生颓废 提交于 2019-12-11 02:38:35

问题


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?


回答1:


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 ?



来源:https://stackoverflow.com/questions/20981691/django-how-to-render-image-with-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!