Django For循环不输出任何东西

时间:2018-11-28 22:25:53

标签: python html django

刚进入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 %}

有人可以指出我要去哪里了,谢谢。

1 个答案:

答案 0 :(得分:1)

在视图中,您可以通过以下行用键Movies加载上下文:

AllMovies = {'Movies': GivenMovies}

因此,在模板中,您应该使用该名称访问变量;更改行:

{% for Movies,Value in AllMovies.items %}

GivenMovies的内容是list而不是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 %}