问题将列表传递给模板Django

时间:2018-09-18 12:07:46

标签: django django-templates django-views

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

我以datetime示例为例,并对其进行了修改,但是它不起作用。

这是我的views.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>

2 个答案:

答案 0 :(得分:1)

您已经从视图中的上下文中删除了now,但是模板中仍然有{% if now %}。将其更改为检查books

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

请注意,在Django中通常不会渲染这样的模板。通常,您将使用渲染快捷方式,并且视图将类似于:

from django.shortcuts import render

def view_books(request): 
    books = Book.objects.all()
    context = {'books': books}
    return render(request, 'index.html', context)

答案 1 :(得分:0)

“ The_books”是一个list,它也是一个迭代器。

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

请参阅我的网站模板代码:

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

代码中的文章就像view.py中的“ the_books”一样,而在模板中,则是由您命名的书。

如果您想显示the_books的项目,请尝试:

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

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