我一直在努力解决一个问题,本网站上的类似问题对我没有帮助。我正在学习Django,我想将一个图像PNG(我用Python生成)打印到HTML页面中(因此,按照Django的规则,我使用HTML模板)。为了创建我的图片,我已经将一些代码写入了一个SEPARATED views.py文件(我称之为views1.py),这里是内容:
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
在我的views.py中,我定义了一个函数,该函数允许用户搜索股票的股票代码。当他提交请求时,用户将在那一刻看到股票的价格,这是我的功能(这个功能有效,我已经测试过了):
# import some packages (for the answer, ignore those that are not related, I have other functions in this views.py file)
from django.shortcuts import render
from django.http import HttpResponse
from yahoo_finance import Share
import datetime as dt
import pandas_datareader.data as web
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def enterTicker(request):
errors = []
if 'q' in request.GET:
q = request.GET['q']
ticker = q
ticker2=Share('%s'%ticker)
pricetoday=ticker2.get_price()
if not q:
errors.append('Enter a valid ticker.')
elif(pricetoday==None):
errors.append('Enter a valid ticker.')
else:
return render(request, 'search_results.html',
{'query': q, 'ticker': q, 'pricenow': pricetoday})
return render(request, 'search_form.html',
{'errors': errors})
在我的urls.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>
有人理解为什么我在views1.py中生成的PNG图片与我的HTML模板之间的链接不起作用?非常感谢,我真的被困在这个