将错误链接到WTForms FieldLists中的右侧字段

时间:2012-07-19 18:03:38

标签: python ajax wtforms fieldlist

我正在使用WTForm来验证我直接从javascript模型提交的表单(通过敲除填充)。在我的表单中,我有一个可以动态添加/删除的银行帐户列表。在python方面我有这样的事情:

class Account(Form):
    acc_name        = TextField('Account', [validators.Length(min=2, max=35)])    

class InformationForm(Form):
    account_list = FieldList(FormField(Account))

收到的用于验证的json数据如下:

'account_list': [{'acc_name': 'aaaaa'}, {'acc_name': 'b'}]}

问题是,当我确认收到类似这样的内容时,无法知道列表中的哪个帐户是错误的来源:

'account_list': [{'acc_name': [u'Field must be between 2 and 35 characters long.']}

如何将错误链接到正确的帐户?

编辑:我最终的方式是我在我的InformationForm类中添加了一个getErrors方法,该类为每个帐户构建一个由唯一ID索引的字典,其中每个帐户的值都是错误。然后我把它作为json返回给我的应用程序。我保持问题是开放的,以防有一个"自然"溶液...

1 个答案:

答案 0 :(得分:2)

FieldList中的每个单独元素都是一个字段。如果FieldList包含TextField,则每个条目都是TextField。如果它包含FormField,则它是FormField(然后包含具有自己字段的表单)可以通过迭代FieldList或访问FieldList的.entries属性来访问FieldList条目。

所以不要看form.account_list.errors看看封闭字段的错误。

所以为了你的用途,这样的事情:

{% for subfield in form.account_list %}
    <!-- subfield in this case is an instance of FormField -->
    {{ subfield.form.acc_name() %}
    {% if subfield.errors %}
        {% for error in subfield.form.acc_name.errors %}
            <p class="error">{{ error }}</p>
        {% endfor %}
    {% endif %}
{% endfor %}

您可能希望abstract this out to a macro而不是为每个专业领域设置执行此操作,如果您需要始终如一地这样做。