python - 如何迭代 Django 模板中的列表?

标签 python django django-templates

<分区>

我将 4 个相同长度的列表和列表的长度传递给我的模板。如何遍历列表?

View .py

def allbooks(request):
    ID = [1,2]
    bookName = ["Python", "Java"]
    author = ["idk", "who"]
    copies = [3,7]
    return render(request, 'allbooks.html',{'ID':ID,'bookName':bookName, 'author':author, 'copies':copies,'range':range(len(ID))})

allbooks.html

{% extends 'base.html' %}

{% block content %}
{% if user.is_authenticated %}
<div>
    <h3>
        List of books:
    </h3>
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Book Name</th>
                <th>Author</th>
                <th>Number of copies</th>
            </tr>
        </thead>
        <tbody>
            {% for x in range %}
                <tr>
                    <td>{{id[x]}}</td>
                    <td>{{bookName[x]}}</td>
                    <td>{{author[x]}}</td>
                    <td>{{copies[x]}}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</div>    
{% else %}
    <h3>You must login to continue.</h3>    
{% endif %}
{% endblock %}

我尝试用 {% forloop.counter0 %} 替换变量 x 但无济于事。我该如何解决这个问题?

最佳答案

将所有列表压缩到一个元组列表中:

 books= zip(ID, bookName, author, copies)
 return render(request, 'allbooks.html',{ "books": books} )

然后在模板中遍历它,例如:

             {% for book in books %}
            <tr>
                <td>{{ book.0 }}</td>
                <td>{{ book.1 }}</td>
                <td>{{ book.2 }} </td>
                <td>{{ book.3 }}</td>
            </tr>
        {% endfor %}

我建议您的图书信息采用更好的结构:

books = [

{ "id":1, "name": "Python", "author":"idk", "copies": 1},
{ "id":2, "name": "Java", "author":"idk2", "copies": 3}

]

比遍历它:

       {% for book in books %}
            <tr>
                <td>{{ book.id }}</td>
                <td>{{ book.name }}</td>
                <td>{{ book.author }} </td>
                <td>{{ book.copies }}</td>
            </tr>
        {% endfor %}

关于python - 如何迭代 Django 模板中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475428/

相关文章:

javascript - 如何将变量从 javascript 发送到 django 中的 View

Python pandas groupby 箱线图重叠

python - Keras - 带权重的多标签分类

django - 如何将自定义 css 类添加到 django-filters 字段

django - 如何在 Django 中制作主从模型/屏幕?

python - 传递参数后如何在模板中的元素中创建id?

java - 从 Twitter JSON Feed 中提取信息

Django 404页面返回200状态码

python - Django naturaltime 本地化错误

Django:如何显示我自己的动态创建的字段