我试图让一个应用程序让用户访问一个站点,提交一个带有位置数据的表单以缩小数据库条目,然后根据该信息显示一个图。用户只需访问索引页面,点击提交按钮即可在表单下方显示图表。在内部,模板调用了绘图视图,该视图使用来自请求的信息来过滤数据并返回一个 .png。在我的索引模板中,我有:
<form action='.' method="get">
State: <input type="text" name="State">
ZIP: <input type="text" name="Zip">
City: <input type="text" name="City">
<input type="submit" value="submit">
</form>
<img src='plot.png?State={{ request.GET.State }}&Zip={{ request.GET.Zip }}&City={{ request.GET.City }}'>
如果我对标签进行硬编码,如下所示:
<img src='plot.png?State=FL&Zip=&City=MIAMI'>
它工作得很好,但我无法让表单将其请求中的信息发送到其下方的标签中。我可以改为让表单指向绘图视图本身,但随后页面会将您带到不受欢迎的图像。我将如何解决这个问题?
编辑:很抱歉不包括 urls.py 和 views.py,他们在这里!
网址.py
urlpatterns = patterns('',
url(r'^$','grapher.views.index', name='index',),
url(r'^plot.png$', 'grapher.views.plot', name='plot'),
)
视图.py
def index(request):
states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID',
'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS',
'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK',
'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV',
'WI', 'WY']
context = RequestContext(request,{'states': states})
return render(request, 'grapher/index.html', context)
def plot(request):
data = scoreData.objects.all()
state = request.GET.get('State','')
postal = request.GET.get('Zip','')
city = request.GET.get('City','')
if state != '':
data = data.filter(state=state)
elif postal != '':
data = data.filter(postal=postal)
elif city != '':
data = data.filter(city=city)
cleanedData = []
for score in data:
cleanedData.append(score.score)
fig = Figure()
ax = fig.add_subplot(1,1,1)
ax.hist(cleanedData,100)
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response