【发布时间】:2023-04-01 08:46:01
【问题描述】:
我想在表格中显示模型的所有对象,其中信息作为表格中的只读字段,每个字段作为表格的一个单元格。
目前我可以在包含所有记录的表格周围呈现表单...
In views: schedule_projects = Record.objects.all()
In template:
<form action="" method="POST">{% csrf_token %}
<table>
<thead>
<tr>
<th>Record</th>
<th>Date</th>
<th>Comment</th>
<th colspan="2">Attached</th>
</tr>
</thead>
{% for record in schedule_projects %}
<tr>
<td>{{record.projectname}}</td>
<td>{{record.date_edited|date:"d-m-Y H:i"}}</td>
<td>{% if record.project_details %}{{record.project_details}}{% else %}{%endif%}</td>
<td>{{record.attached_files|default_if_none:'0'}}</td>
<td><input type="checkbox" name="record" value="{{record.plan_delete}}"></td>
</tr>
{% endfor %}
</table>
<button type="submit" name="plan_delete">Add to delete schedule</button></form>
我不想像这样手动执行此操作,而是希望使用 forms.py 中内置的表单来执行此操作 - 因为它提供了验证、csrf 和其他方法。
我希望表单在没有标签的情况下呈现每个字段,并且作为只读文本字段,而不是作为输入字段。如果初始表单中的值为 true,我还希望通过勾号激活具有布尔字段 plan_delete=True 的记录,以便在提交表单时可以在视图中添加更多带有 plan_delete 布尔值的记录。它应该看起来像这样。
Record Date Comment Attached
John Doe 01/02/2017 Current 3 (checkbox)
Peter Piper 02/01/2017 Bla. bla 5 (checkbox)
Etc.. 11/12/2017 Etc.. 0 (checkbox)
Add to delete schedule (submit)
我尝试过使用 as_table 和 modelform 表单,但似乎如此简单的事情很快就会变得非常复杂。
所以我的问题是,我的方式是“正确”、最简单的方式吗?还是我错过了一些简单的关于 forms.form 或 modelform 添加到 forms.py 的好处?如何呈现一个包含我所有记录的表单以及 plan_delete 字段的复选框 - 以便我可以在我的视图中处理它。
【问题讨论】: