首页 > 解决方案 > 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

标签: pythonhtmldjangodjango-forms

解决方案


如果不向表单添加属性,我看不到一种简单的方法。最后,在您的__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'.


推荐阅读