首页 > 解决方案 > 将列表传递给模板 Django 的问题

问题描述

我正在尝试将 views.py 中的书籍列表传递给 html 模板。

我采用了日期时间示例并对其进行了修改,但它不起作用。

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

标签: djangodjango-templatesdjango-views

解决方案


您已从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)

推荐阅读