Python DJANGO:将PNG图片显示到HTML模板中
我一直在努力解决一个问题,而这个网站上类似的问题对我没有帮助。我正在学习Django,我想将一个图像PNG(我用Python生成)打印到一个HTML页面中(因此,按照Django的规则,我使用一个HTML模板)。为了创建我的图片,我在一个单独的views.py文件(我称之为views1.py)中编写了一些代码,内容如下:Python DJANGO:将PNG图片显示到HTML模板中,python,html,django,Python,Html,Django,我一直在努力解决一个问题,而这个网站上类似的问题对我没有帮助。我正在学习Django,我想将一个图像PNG(我用Python生成)打印到一个HTML页面中(因此,按照Django的规则,我使用一个HTML模板)。为了创建我的图片,我在一个单独的views.py文件(我称之为views1.py)中编写了一些代码,内容如下: from pylab import figure, axes, pie, title from matplotlib.backends.backend_agg import F
from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib.pyplot
from django.http import HttpResponse
def test_matplotlib(request):
f = figure(figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
matplotlib.pyplot.close(f)
return response
在my views.py中,我定义了一个函数,允许用户搜索股票的行情。当他提交请求时,用户将看到当时的股票价格,这是我的函数(此函数有效,我已经测试过):
在我的URL.py文件中,我执行了以下操作:
from django.conf.urls import include, url
from django.contrib import admin
from mysite import views, views1
urlpatterns = [
...,
url(r'^search/$', views.enterTicker),
...,
]
最后,我还有我的模板search_results.html:
<html>
<head>
<title>Book Search</title>
</head>
<body>
<p>You searched for: <strong>{{ query }}</strong></p>
{% if ticker %}
<p>The price of {{ ticker }} in this moment is {{ pricenow }}.</p>
<img src="../views1.py" />
{% else %}
<p>No tickers matched your search criteria.</p>
{% endif %}
</body>
</html>
图书查询台
您搜索了:{{query}
{%if ticker%}
此时此刻{{ticker}}的价格是{{pricenow}
{%else%}
没有与您的搜索条件匹配的票证。
{%endif%}
有人知道为什么我在views1.py中生成的PNG图片和我的HTML模板之间的链接不起作用吗?非常感谢,我真的被这个问题困扰了这真的是你的img的
src
值吗?这毫无意义;它应该链接到一个URL,而不是Python文件。这正是我所想的,然后我在这里找到了一个答案:有人说你就是这样做的,我发现很奇怪,你误解了链接告诉你的内容。它说src应该是“该视图url的路径”;换句话说,为test\u matplotlib
视图提供服务的URL。您应该在URL.py中添加一个使用views1.test\u matplotlib
的条目,并在src中使用该URL。非常感谢Daniel,我确信错误很小,而且很尴尬
<html>
<head>
<title>Book Search</title>
</head>
<body>
<p>You searched for: <strong>{{ query }}</strong></p>
{% if ticker %}
<p>The price of {{ ticker }} in this moment is {{ pricenow }}.</p>
<img src="../views1.py" />
{% else %}
<p>No tickers matched your search criteria.</p>
{% endif %}
</body>
</html>