【问题标题】:Problem passing list to a template Django将列表传递给模板 Django 的问题
【发布时间】:2018-09-18 12:07:46
【问题描述】:

我正在尝试将 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>

【问题讨论】:

标签: django django-templates django-views


【解决方案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)

【讨论】:

  • 刚刚复制并粘贴了您的答案。还是不行。
  • “无法正常工作”信息不足以让我们帮助您调试问题。如果您的数据库中有书籍,并且您的模板使用上下文 {'books': the_books} 呈现,那么上面的模板 sn-p 将显示它们。
【解决方案2】:

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

我的代码中的文章就像你在 view.py 中的“the_books”,而在模板中,由你命名书籍。

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

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

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

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 2011-08-17
    • 2014-08-14
    • 2012-11-01
    • 1970-01-01
    • 2017-03-02
    • 2021-02-11
    • 2021-07-26
    相关资源
    最近更新 更多