django - 将列表传递给模板 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>
解决方案
您已从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)
推荐阅读
- apache-camel - 带有交换和路由键的骆驼 amqp uri
- php - 使用 unoconv 将 .csv 文件转换为 .xls 时缺少标题
- azure - 是否可以从 docker compose 卷中指定文件夹路径?
- sql - sql中的按位运算
- postgresql - psycopg2.errors.UndefinedColumn:列已排除。编号不存在
- video - 为用户跟踪和保存视频进度
- java - 当 Activity Swipe 上的 CardStackView 时如何停止适配器上的 MediaPlayer?
- c# - C# 控制台应用程序不会在其他人的计算机上运行
- html - How to Create Date Count timer selecting date from the date picker input and show the difference of selected date to current date
- laravel - Laravel - 如何将所有导入错误保存到表中