如何使用Django中的for循环创建选项卡

2024-03-29 09:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django的初学者,我正试图使用名为law.html的html模板创建一个自定义表。在law.html中,我有以下代码。在

<table class="table table-striped">
<thead>
    <tr>
        <th>Solicitor_Names</th>
        <th>Offices</th>
        <th>Addresses</th>
        <th>Primary_Role</th>
        <th>Secondary_Role</th> 
        <th>Other_Role</th>
        <th>Other_Role_1</th>  
        <th>Other_Role_2</th>
        <th>Other_Role_3</th>
        <th>Other_Role_4</th>        
    </tr>
</thead>
<tbody>
    {% for name in all_data.Solicitor_Name %} 
    <tr>
        <td>{{ name }}</td>
    <tr>
    {% endfor %}
    {% for office in all_data.Office %} 
    <tr>
        <td>{{ office }}</td>
    <tr>
    {% endfor %}
</tbody>

输出完美地生成了所需的表标题。另外,Solicitor_Name列中填充了所需的数据。但是,我尝试将Office数据放入下一列失败。相反,数据继续填充Solicitor_Name列下的单元格。我如何格式化代码,这样我就可以得到像这样的期望输出?在

^{pr2}$

这是我的视图.py在

def law_view(request, *args, **kwargs):
 all_data = combine_data()
 return render(request, "law.html", {'all_data': all_data})

Tags: 数据代码namedatahtmltablealltr
1条回答
网友
1楼 · 发布于 2024-03-29 09:51:48

你必须一行一行地构造你的表,而不是一列一列的。这也意味着all_data应该是行的列表,而不是列的字典(现在看来是这样)。所以你想这样构造all_data

[
    {'name': 'Mr. Shaw', 'office': 'Orange LLP', 'address': '123 Main Str'},
    {'name': 'Bill', 'office': 'Apple LLP', 'address': '124 Bone St'},
 ... ]

而不是这样:

^{pr2}$

如果您确定列表的长度都相同(看起来是这样),可以使用以下方法将第二种格式转换为第一种格式:

^{3}$

或者在DataFrame上肯定有一个函数来做这个(transpose()?)在

然后在模板中只有一个循环:

{% for solicitor in all_data %}
    <tr><td>{{ solicitor.name }}</td><td>{{ solicitor.office }}</td>...</tr>
{% endfor %}

相关问题 更多 >