python - Django For循环不输出任何东西
问题描述
刚进入 Django,我很困惑为什么这个 for 循环没有打印任何东西。我没有收到任何错误,这是我的代码;
我的浏览页面;
GivenMovies = [
{
'Name': 'Thor',
'Genre': 'Action',
'Rating': '7.0',
'Content': 'Mad Movie',
'Date_Posted': 'January 18, 2017'
},
{
'Name': 'Constantine',
'Genre': 'Action, Sci-Fi',
'Rating': '7.2',
'Content': 'Another madness of a movie',
'Date_Posted': 'January 18, 2015'
}
]
def MainPage(request):
AllMovies = {'Movies': GivenMovies}
return render(request, 'Movies/HomePage.html', AllMovies)
我的forloop;
{% extends "Movies/Parent.html" %}
{% block content %}
<h1> is showing</h1>
{% for Movies,Value in AllMovies.items %}
<h1> {{ Movies.Name }} </h1>
<p> Genre: {{ Values.Genre }} </p>
<p> Rating: {{ Values.Rating }}</p>
<p> Content: {{ Values.Content }} </p>
<p> Posted on: {{ Values.Date_Posted }} </p>
{% endfor %}
{% endblock content %}
有人可以指出我哪里出错了,谢谢。
解决方案
在视图中,您Movies
通过此行使用键加载上下文:
AllMovies = {'Movies': GivenMovies}
因此,在您的模板中,您应该使用该名称访问变量;换行:
{% for Movies,Value in AllMovies.items %}
但是: 的内容GivenMovies
不是list
a dict
,所以调用.items
也不起作用。只需遍历列表,也许使用这个:
{% for item in Movies %}
<h1> {{ item.Name }} </h1>
<p> Genre: {{ item.Genre }} </p>
<p> Rating: {{ item.Rating }}</p>
<p> Content: {{ item.Content }} </p>
<p> Posted on: {{ item.Date_Posted }} </p>
{% endfor %}
推荐阅读
- ruby-on-rails - RSpec 和 Capybara:如何让 have_css 带有文本:忽略文本中的换行符
- javascript - 如何在 Node.js 中正确设置猫鼬方法 createConnection
- cypress - 如何使用赛普拉斯将元素移动到块中?
- node.js - 在 Node.js 中如何注意到缺少的功能?
- list - 在 XML 文件中保存游戏对象的数据时出现问题
- google-apps-script - 在没有 CORS 限制的情况下嵌入可编辑的 Google 表格
- javascript - 如何从不同的导出函数中使用 this.skip()
- python - python多进程无法获取属性
- android - firebase 中特定路径的 getkey()
- git - 从其他远程存储库克隆分支,以便我可以覆盖我自己的存储库