我是Django的新手,我正在尝试在视图中显示matplotlib图像和一些数据。 matplotlib是在不同的python文件中创建的。
这是matplotlib代码:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np
from django.http import HttpResponse, HttpResponseRedirect
def plot_playoutcomes(playdata):
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
x = np.arange(-2,1.5,.01)
y = np.sin(np.exp(2*x))
ax.plot(x, y)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
它生成一个简单的图形。这是views.py:
def getinput(request):
if request.method == 'POST':
form = get_data(request.POST)
if form.is_valid():
down = form.cleaned_data['get_down']
ytg = form.cleaned_data['get_ytg']
yfog = form.cleaned_data['get_yfog']
map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg)
fig = plot_playoutcomes(map_data)
context = {'form': form, 'query_data': map_data, 'img': fig}
return render(request, 'play_outcomes/output.html', context)
else:
form = get_data()
return render(request, 'play_outcomes/getinput.html', {'form': form})
def output(request):
return render(request, 'play_outcomes/output.html', context)
它从表单中获取数据,使用它来查询数据集。问题是,当我尝试显示模板时,图像{{img}}
不会出现。
在网页上我得到了这个:<HttpResponse status_code=200, "image/png">
但不是图片。救命啊!