Django For循环不输出任何内容

2024-09-29 19:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

刚进入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)

我的前环

{% 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 %}

有人能指出我哪里出错了吗,谢谢。你知道吗


Tags: namefordaterequestactioncontentmoviesh1
1条回答
网友
1楼 · 发布于 2024-09-29 19:13:43

在视图中,通过以下行加载带有键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 %}

相关问题 更多 >

    热门问题