Django 将任何查询显示为 html 表格

问题描述 投票:0回答:1

我想将数据库中的简单查询显示为 HTML 表。但我在 Django 数据管理的模板或一般逻辑中遗漏了一些东西。

首先我正在创建一个这样的模型:

class Book(models.Model):
    title = models.CharField(max_length=128, unique =True)
    quantity = models.IntegerField(default=1)

然后使用包含查询的列名称和查询对象的上下文创建视图,例如:

def books(request):
    context = {"rows":Book.objects.all(),"fields" : Book._meta.get_fields()}
    return render(request,"blog/books.html",context)

最后,我尝试迭代模板中查询的值,以便将它们放入 HTML 表中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Our Books</title>
</head>
<body>

    <table border="1">
        <thead>
            <tr>
                {% for field in fields %}
                    <th>{{ field.verbose_name }}</th>
                {% endfor %}
            </tr>
        </thead>
        <tbody>
            {% for row in rows %}
                <tr>
                    {% for field in fields %}
                        <td>{{ row[field] }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </tbody>
    </table>

</body>
</html>

添加表格标题工作正常,但这部分不起作用:

{% for row in rows %}
    <tr>
         {% for field in fields %}
             <td>{{ row[field] }}</td>
         {% endfor %}
    </tr>
{% endfor %}

我尝试过不同的事情,但没有任何运气:

  1. row[field]
  2. row[field.verbose_name]
  3. row.field
  4. {{ row.__dict__.get(field.verbose_name) }}
  5. 还有更多

我应该如何进行?我不想对模板中的列名称进行硬编码,我想迭代它们,以便它适用于任何表。

python-3.x django django-views django-templates
1个回答
2
投票

Django 的模板语言支持下标(即

x[y]
),这是故意这样做的,以防止人们在模板中编写业务逻辑。可以使用 Jinja 作为模板语言,但这不是必需的,并且在某种程度上会适得其反,正是为了防止在模板中编写业务逻辑。

但是,我们可以使用以下方法“准备”视图中的数据:

def books(request):
    fields = Book._meta.get_fields()
    context = {
        'rows': [
            [getattr(book, field.name) for field in fields]
            for book in Book.objects.all()
        ],
        'fields': fields,
    }
    return render(request, 'blog/books.html', context)

然后渲染:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Our Books</title>
</head>
<body>

    <table border="1">
        <thead>
            <tr>
                {% for field in fields %}
                    <th>{{ field.verbose_name }}</th>
                {% endfor %}
            </tr>
        </thead>
        <tbody>
            {% for row in rows %}
                <tr>
                    {% for cell in row %}
                        <td>{{ cell }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </tbody>
    </table>

</body>
</html>

注意:可能值得一看

django-tables2
 [GitHub] 以有效的方式呈现表格。

© www.soinside.com 2019 - 2024. All rights reserved.