python - How to create table with dynamically rows and columns with number of fields in template Django
问题描述
I want to create dynamically rows and columns table in Django with number. Like the attached picture below
<table border="1">
{% for i in row %}
<tr>
{% for x in columns %}
<td>????</td>
{% endfor %}
</tr>
{% endfor %}
</table>
解决方案
根据您想要 3 列和 n 行的图片,您可以将列表拆分为具有 3 个元素的子列表。
在您的 views.py 中执行此操作:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 3 #elements per sublist
final_list = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )]
确保您将 final_list 传递给您的模板。
在模板中,您可以遍历列表并构建您的表格,如:
<table>
{% for sublist in final_list %}
<tr>
{% for element in sublist %}
<td>element</td>
{% endfor %}
</tr>
{% endfor %}
</table>
推荐阅读
- .htaccess - htaccess 将查询字符串附加到所有 URL
- django - Django:在列表视图中包含一个表单
- sml - 在列表中显示多次出现的项目,sml
- laravel - laravel 删除数据库中的数据
- ios - 尝试将 Google AdMob 集成到 iOS 上的 libgdx 游戏中会导致“找不到框架 GoogleUtilities”
- r - 将数据框中的文本信息拆分为单个单词并检测它们是否是字典 R 的一部分
- php - Mysql,将PHP中的选项存储为数组
- java - 从命令行运行本地(反应器)maven插件
- php - 富文本编辑器 Laravel Trix 的未知错误
- r - 对两条曲线之间的数据进行子集化