首页 > 解决方案 > 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 %}

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

标签: pythonhtmldjango

解决方案


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

AllMovies = {'Movies': GivenMovies}

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

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

但是: 的内容GivenMovies不是lista 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 %}

推荐阅读