排序WTForms form.errors字典 [英] Sorting WTForms form.errors dict

查看:425
本文介绍了排序WTForms form.errors字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

forms.errors字典似乎是按字段名排序的,而不是按照它们在表单本身中声明的
顺序。

例如,

  class ProductForm(Form):
code = TextField('Code',validators = [Required()])
description = TextField('Description',validators = [Required(),Length(max = 100)])
amount = DecimalField('Amount',validators = [Required(),NumberRange(min = 0.00,max = 1000000.00)])
vat_percentage = DecimalField('VAT%',validators = [Required(),NumberRange(min = 0.00,max = 100.00)])
inactive_date = DateField date',validators = [Optional()])

其中的form.errors如下所示:

  {'amount':['Amount is required'],'code':['Code is invalid。'],
'description':['Description is required'],'vat_percentage':['VAT%is required']}

我想要做的是在订单中打印错误,因为它们是在表格中订购的



这可能吗?

解决方案

字典本身是无序的(在Python中)。但是,WTForms包括字段中的每个字段的错误以及表单,它确保字段可以按声明的顺序枚举。因此,不是枚举 form.errors ,您可以遍历 form ,然后遍历每个字段

 用于表单中的字段:
用于错误in field.errors:
#显示错误


The forms.errors dict seems to be sorted on field name, and not on the order they are declared in the form itself.

E.g.

class ProductForm(Form): 
    code = TextField('Code', validators=[Required()]) 
    description = TextField('Description', validators=[Required(), Length(max=100)]) 
    amount = DecimalField('Amount', validators=[Required(), NumberRange(min=0.00, max=1000000.00)]) 
    vat_percentage = DecimalField('VAT %', validators=[Required(), NumberRange(min=0.00, max=100.00)]) 
    inactive_date = DateField('Inactive date', validators=[Optional()]) 

Which produces the form.errors like:

{'amount': ['Amount is required'], 'code': ['Code is invalid.'], 
'description': ['Description is required'], 'vat_percentage': ['VAT % is required']} 

What I would like to do is print the the errors in the order as they are ordered in the form.

Is this possible?

解决方案

Dictionaries are inherently unordered (in Python). However, WTForms includes each field's errors on the field as well as the form and it does guarantee that the fields can be enumerated in declared order. So rather than enumerating form.errors you can loop over form and then loop over each field.errors to get them in order:

for field in form:
    for error in field.errors:
        # Display error

这篇关于排序WTForms form.errors字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆