【问题标题】:Python dictionary inaccessible in django template在 django 模板中无法访问 Python 字典
【发布时间】: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 这是正确答案,你应该发布它

标签: django django-templates


【解决方案1】:

在您传递给模板的内容中没有 output 这样的东西。 output 只是您为上下文字典指定的名称。模板接收该字典的内容。因此,您可以直接使用 {{ result }}{{ end_time }}

【讨论】:

  • 嗨丹尼尔,我尝试了你的解决方法,但不幸的是它没有奏效。尽管我在@Paandittya 上面的评论的帮助下使它工作。以下是我为获得所需所做的事情。在views.py中return render(request, 'fibohome/home.html', {'output':output})在模板home.html中{{ output.result }}
  • 您是否删除了{% if output %} 检查?
  • 没有丹尼尔。如果块仍然存在。
  • 嗯,这就是原因;正如我所说,output 不存在。
  • 是的。它也按你的方式工作!但我需要 if 块。非常感谢您的时间和建议。
猜你喜欢
  • 1970-01-01
  • 2021-10-17
  • 2014-02-08
  • 1970-01-01
  • 2021-04-10
  • 2013-11-13
  • 1970-01-01
相关资源
最近更新 更多