通过模板渲染图像时Django Unicode错误

时间:2016-08-01 07:23:05

标签: django python-2.7 matplotlib django-templates django-views

我在django(1.9)Python 2.7.10中渲染图像。它工作正常。

  

views.py

canvas = FigureCanvas(fig)
response = django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
plt.close(fig)
return response

上面的代码总是从行的开头在浏览器中发布Image。我想将图像定位到浏览器中的新位置。我尝试在模板中传递响应变量。

  

views.py

canvas = FigureCanvas(fig)
response = django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
plt.close(fig)
context = {'response': response}
return render(request, 'index.html', context)
  

的index.html

<div align="center" style="text-align:center;">{{ response }} </div>

这里的问题是我收到错误:

  

&#39; UTF8&#39;编解码器不能解码位置27中的字节0x89:无效的起始字节。你传递了HttpResponse status_code = 200,&#34; image / png&#34; (class&#39; django.http.response.HttpResponse&#39;)

1 个答案:

答案 0 :(得分:0)

您需要为自己的视图设置自己的网址(请注意,这可能是您列出的有效视图),在urls.py中添加:

  url('^show_graph/$', yourview, name="show_graph"),

然后你可以通过输入index.html:

在你的html中显示这个图像
<img src={% url "show_graph" %} height="400" width="400">
相关问题