【问题标题】:How do I reference a matplotlib plot returned from a view in an html template in Django?如何引用从 Django 中的 html 模板中的视图返回的 matplotlib 图?
【发布时间】:2018-03-14 15:45:43
【问题描述】:

我正在尝试在 django 中以交互方式显示 matplotlib 中的绘图。从这个answer,我看到我可以使用以下代码从视图发送图:

response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response

所以视图将绘图作为Httpresponse 发送,但我如何在模板的 html 代码中引用它?我猜它会是这样的,但我很难找到 html 代码的示例:

<img src={ some reference to the plot here }>

再次,我想我可以生成带有视图的绘图,但不确定如何在 html 模板中引用该输出。

【问题讨论】:

  • 你没有抓住重点。 src 需要指向为视图提供服务的 URL。
  • 所以...在那个视图中,如果我设置 template_name = "app/plot.html" 那么情节的 src 将是那个路径?我会试试的。感谢您的帮助。
  • 不,我根本不是这么说的。有关更多解释,请参阅我的答案。
  • 哦...我在urlpatternspath()的urls.py中设置的URL
  • 我现在明白了。再次感谢!

标签: python html django matplotlib


【解决方案1】:

视图由 URL 提供。这个视图的存在纯粹是为了提供图像的内容,因此你应该简单地使用它的 URL 作为你的 img 标签中的 src。例如:

urlpatterns = [
    path('path/to/my/image', views.my_image, 'my_image')
]

...

def my_image(request, ...):
    response = HttpResponse(mimetype="image/png")
    # create your image as usual, e.g. pylab.plot(...)
    pylab.savefig(response, format="png")
    return response

...

<img src="{% url "my_image" %}">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多