Sorting WTForms form.errors dict

孤人 提交于 2020-01-03 17:10:45

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/15427092/sorting-wtforms-form-errors-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!