Sort WTForms form.errors dict

Form dictors appear to be sorted by field name, not what they are declared on the form itself.

eg.

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()]) 

Creates a form. For instance:

 {'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 errors in the order, since they are ordered on the form.

Is it possible?

+4
source share
1 answer

Dictionaries are inherently disordered (in Python). However, WTForms includes all field errors in the field as well as the form, and this ensures that the fields can be listed in declared order. So instead of enumerating form.errors you can execute a form loop and then field.errors over all field.errors to get them in order:

 for field in form: for error in field.errors: # Display error 
+4
source

Source: https://habr.com/ru/post/1469431/


All Articles