【发布时间】:2019-03-14 20:38:03
【问题描述】:
我想使用从视图传递到模板的键来访问字典值。尽管经过几个小时的搜索和挣扎,我仍然无法预测原因。下面是图片。
views.py 中的 post 方法
def post(self, request):
value = request.POST['value']
if value is '':
return redirect('home')
else:
start_time = time.time()
obj = CalcClass(value)
result=obj.calculate()
end_time = time.time() - start_time
output={}
output['result']=result
output['end_time']=end_time
return render(request, 'fibohome/home.html', output)
模板主页.html
<div class="col-sm-6 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
{% if output %}
<h3>Output</h3>
<h4>{{ output.result }}</h4>
<h3>Time required</h3>
<h4>{{ output.end_time }}</h4>
{% else %}
<h3>None</h3>
{% endif %}
</div>
</div>
</div>
前端 UI- 提交任意数字后,它只显示无。虽然我在控制台中得到输出。
希望我提供了足够的信息。谢谢!
【问题讨论】:
-
在帖子中添加键值对字典,这就是它在模板中无法访问的原因。如果您使用 get 请求,那么模板可以访问它。
-
纠正你在views.py中的最后一行,像这样
return render(request, 'fibohome/home.html', {'output': output}) -
@Paandittya 这是正确答案,你应该发布它