【问题标题】:Django Unicode Error While Rendering Image through template通过模板渲染图像时出现 Django Unicode 错误
【发布时间】:2016-12-06 04:40:03
【问题描述】:

我正在 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

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

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>

这里的问题是我得到了错误:

'utf8' 编解码器无法解码位置 27 中的字节 0x89:无效的起始字节。你传入了 HttpResponse status_code=200, "image/png" (class 'django.http.response.HttpResponse')

【问题讨论】:

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


    【解决方案1】:

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

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

    然后你可以在你的 html 中通过放入 index.html 来显示这个图像:

    <img src={% url "show_graph" %} height="400" width="400">
    

    【讨论】:

    • 给我错误“标签开始未关闭”这里的 url 是什么变量?
    • url 是 django 模板标签:docs.djangoproject.com/en/1.9/ref/templates/builtins/#url - 对于错误 - 请检查模板中的标点符号和空格。代码应该像 Iisted 一样工作。
    • 感谢您的帮助,但图片仍未显示...空白页
    • 我正在使用 Pycharm ...它说 url 属性 url 不允许在这里我错过了什么
    • 您也可以硬编码视图的路径(尽管不推荐这样做)。 。路径应该是有效视图的 url。
    猜你喜欢
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多