Python wtforms中的字段字典
我想知道是否可以使用wtforms在表单中创建字段字典 原因是我有一个位置字典,我使用jinja将其呈现到一个表中。在使用wtforms之前,我可以轻松处理以下各项的输入:Python wtforms中的字段字典,python,dictionary,field,wtforms,Python,Dictionary,Field,Wtforms,我想知道是否可以使用wtforms在表单中创建字段字典 原因是我有一个位置字典,我使用jinja将其呈现到一个表中。在使用wtforms之前,我可以轻松处理以下各项的输入: {% for locKey, loc in locDict.iteritems() %} <tr> <td>{{ loc['name'] }}</td> <td><input type="text" id="{{ locKey }}" name="locK
{% for locKey, loc in locDict.iteritems() %}
<tr>
<td>{{ loc['name'] }}</td>
<td><input type="text" id="{{ locKey }}" name="locKey"></td>
</tr>
{% endfor %
{form.loclocOne}}
等。这是相当难看的,但迄今为止我能看到的唯一可行的解决方案from wtforms.validators import NumberRange
from wtforms import Form, IntegerField
# dictionary of locations with certain attributes
locDict = {}
locDict['locOne'] = {'name': 'Location One', 'popn': 1000}
locDict['locTwo'] = {'name': 'Location Two', 'popn': 2000}
locDict['locThree'] = {'name': 'Location Three', 'popn': 3000}
class testForm(Form):
# standard field
normalField = IntegerField('Normal Field', validators=[NumberRange(min=0, max=100)])
# initiate dictionary of fields
locFields = {}
for locKey, loc in locDict.iteritems():
locFields[locKey] = IntegerField(loc['name'], validators=[NumberRange(min=0, max=loc['popn'])])
# test the form
testFormInstance = testForm()
print testFormInstance.normalField
print testFormInstance.locFields['locOne']
print testFormInstance.locFields['locTwo']
print testFormInstance.locFields['locThree']
# returns:
#<input id="normalField" name="normalField" type="text" value="">
#<UnboundField(IntegerField, ('Location One',), {'validators': [<wtforms.validators.NumberRange object at 0x7f8367970050>]})>
#<UnboundField(IntegerField, ('Location Two',), {'validators': [<wtforms.validators.NumberRange object at 0x7f8367963f90>]})>
#<UnboundField(IntegerField, ('Location Three',), {'validators': [<wtforms.validators.NumberRange object at 0x7f83679700d0>]})>
{% for locKey, loc in locDict.iteritems() %}
<tr>
<td>{{ loc['name'] }}</td>
<td>{{ form.loc{{ locKey }} }}</td>
</tr>
{% endfor %}