本文介绍了Django:如何使用模板渲染图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

目标:我想使用模板显示生成的.png图像。

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

访问 gen_chart 视图显示了一个漂亮的饼图。然而,我想使用模板来渲染,所以我可以在结果页面(标签,描述,标题和其他html内容)中添加更多的数据。

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

但是您可能已经猜到,我遇到错误 UnboundLocalError:在赋值之前引用的局部变量'response',因为 response 变量在创建 c 时不存在。

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?

推荐答案

由于您已经有一个工作 gen_chart 视图,创建您的图像为png为什么不只是添加一个

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" %}' />

到您的HTML模板并呈现正常?你是为了使你的生活变得困难吗?

to your HTML template and render it normally ? You are you trying to make your life difficult ?

这篇关于Django:如何使用模板渲染图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:52