将字典列表存储为HTML表格

时间:2016-05-05 23:18:12

标签: python django dictionary

所以我想将django中的词典列表存储为HTML表格,以便我可以将它与django_tables2一起使用。什么是最好的方式来解决这个问题?现在我有这个:

我的view.py

context = {'campaigns': campaigns, 'ad_account': ad_account}

return render(request, 'index.html', context)

广告系列的展示位置如下:

[<Campaign> { "effective_status": "PAUSED", "id": "6038662580877", "name": "test22", "objective": "APP_ENGAGEMENT" }, <Campaign> { "effective_status": "PAUSED", "id": "6038659889677", "name": "just a test", "objective": "APP_ENGAGEMENT" }]

我无法将当前方法与django_tables一起使用,因为它只接受一个表。我现在做的是粘贴在下面,并在1页中生成一个完整的表格,这是不可行的,因为添加了更多的数据。

<table class="table table-bordered table-striped" id="campaigns">
    <thead>
    <tr>
        <th> #</th>
        <th> Name</th>
        <th> Objective</th>
        <th> Effective Status</th>
    </tr>
    </thead>
    <tbody>
    {% for campaign in campaigns %}
        <tr>
            <td> {{ forloop.counter }} </td>
            <td>
                <a href="/ad/{{ ad.id }}/campaigns/{{ campaign.id }}/ad_sets">
                    {{ campaign.name }} </a>
            </td>
            <td> {{ campaign.objective }}</td>
            <td> {{ campaign.effective_status }} </td>
        </tr>
    {% endfor %}
    </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

django_table contains examples的文档,用于使用dict个对象列表构建Table

  

我们将使用dicts列表演示一个示例。定义表时,必须声明每列。如果您的数据与模型中的字段匹配,则可以通过Table.Meta.model选项自动声明列,但对于非查询集数据,您可能希望手动声明它们:

import django_tables2 as tables

data = [
    {'name': 'Bradley'},
    {'name': 'Stevie'},
]

class NameTable(tables.Table):
    name = tables.Column()

table = NameTable(data)

然后就像以前一样使用模板中的表格。

相关问题