Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将列表传递给模板Django时出现问题_Django_Django Templates_Django Views - Fatal编程技术网

将列表传递给模板Django时出现问题

将列表传递给模板Django时出现问题,django,django-templates,django-views,Django,Django Templates,Django Views,我正在尝试将图书列表从views.py传递到html模板 我以datetime为例进行了修改,但它不起作用 以下是我的视图.py: def theBooks(request): t = template.loader.get_template('templates/index.html') the_books = Book.objects.all() c = template.Context({'books': the_books}) html = t.rend

我正在尝试将图书列表从views.py传递到html模板

我以datetime为例进行了修改,但它不起作用

以下是我的视图.py:

def theBooks(request): 
    t = template.loader.get_template('templates/index.html')
    the_books = Book.objects.all()
    c = template.Context({'books': the_books})
    html = t.render(c)
    return HttpResponse(html)
我的模板是:

<!DOCTYPE html>
 <html lang="es">
 <head>
    <meta charset="UTF-8">
    <title>Current Time</title>
 </head>
 <body>

    {# This is a comment #}

    {# check the existence of now variable in the template using if tag #}

  {% if now %}   
     <p>The books are: {{ books }}</p>
  {% else %}               
    <p>now variable is not available</p>
  {% endif %}

 </body>
 </html>

当前时间
{这是一个评论}
{#使用if标记#检查模板中是否存在now变量}
{%if now%}
这些书是:{{books}

{%else%} 现在变量不可用

{%endif%}
您已经从视图中的上下文中删除了
now
,但模板中仍然有
{%if now%}
。改为选中
书籍

{% if books %}   
    <p>The books are: {{ books }}</p>
{% else %}               
    <p>There are no books</p>
{% endif %}

“the_books”是一个列表,也是一个迭代器

您可以尝试向代码中添加循环

请查看我的网站模板代码:

{% for item in article %}
<div class="blog-post">

<h2>{{ item.title }}</h2>

<p style="font-size: 12pt;">
<a style="border: 2px solid black;color: black">&nbsp;{{ item.type }} </a>
<i>&nbsp;&nbsp;Posted by GYH on {{ item.data }} {{ item.time }}</i></p>

<a href="article/{{ item.id }}" class="btn btn-default btn-lg ">Read More <i class="fa fa-angle-right"></i></a>
</div>
{% endfor %}
{%用于文章%中的项目]
{{item.title}

{%endfor%}

我的代码中的文章与view.py中的“The_books”一样,而在模板中,由您命名为books

如果要显示_书籍的项目,请尝试:

{% for book in books%}
    <a>book</a>
{% end for %}
{%forbook-in-books%}
书
{%end for%}

顺便说一句:dict中的值必须等于html文件中的值。

{'books':the:books}应该是
{'books':the_books}
我想在复制和粘贴您的答案之前会问类似的问题。仍然不工作。“不工作”对于我们来说不足以帮助您调试问题。如果数据库中有书籍,并且模板是使用上下文
{'books':the_books}
呈现的,则上面的模板片段将显示它们。
{% for book in books%}
    <a>book</a>
{% end for %}