python - Django Form循环遍历表单字段,但在html行中显示每个字段的1
问题描述
我有一个表单,它根据我的 HTML 中的变量数动态创建多个字段,然后循环遍历表单以显示字段,但我需要像这样:
第 1 行 =“字段 1,字段 2”
相反,它就像:
第 1 行 = “字段 1,字段 1” 第 2 行 = “字段 2,字段 2”
表格代码:
参加表格类(forms.ModelForm):
class Meta:
model = Attending
fields = ('name', 'type')
def __init__(self, *args, **kwargs):
self.ticket_count = kwargs.pop('count')
super(AttendingForm, self).__init__(*args, **kwargs)
for i in range(1, self.count):
self.fields['%d name' % i] = forms.CharField()
self.fields['%d type' % i] = forms.ChoiceField()
HTML 代码片段:
<form method="post">
<section>
<h1>Manage Attendees</h1>
<div class="content-section">
{% for field in form %}
<div class="form-field">
<label for="visitor_name">Name
{{ field }}
</label>
</div>
<div class="form-field">
<label for="visitor_name">Type</label>
{{ field }}
</div>
{% endfor %}
<div class="form-field">
<input type="submit" value="Submit" class="button button-black">
</div>
</div>
</section>
</form
解决方案
如果不向表单添加属性,我看不到一种简单的方法。最后,在您的__init__()
方法中,添加一个新的字典列表:
self.ordered_fields = [{
'name': self.fields['%d name' % i],
'type': self.fields['%d type' % i]} for i in range(1, self.count)]
然后在您的模板中:
{% for item in form.ordered_fields %}
Name: {{ item.name }}
Type: {{ item.type }}
{% endfor %}
注意:请勿在字段名称中使用空格,这可能会导致您提交的数据出现问题。使用'%d-type'
而不是'%d type'
.
推荐阅读
- c# - Entity Framework Core 通过 SSH 隧道连接到 MSSQL 数据库
- perl - Perl dbi (select) 获取数组中的空字符串
- node.js - Babel 可以使用 Webpack 编译,但不能使用 Jest
- javascript - 按字母表排列在不同列中的垂直顺序
- python - 如何在 Django restframe 工作中获取最后更新的产品?
- javascript - 如何开发搜索选项以在 MVC 视图表中按列搜索
- flutter - 如何更改 TextField 中字符串输入的颜色?
- ember.js - Ember-models-table 插件在尝试使用“routeName”属性时抛出 ember 警告错误
- wordpress - 使用 Docker-compose 的 Wordpress 数据库连接错误
- java - 如何修复此代码的运行时错误?