wtforms Form class subclassing and field ordering

后端 未结 6 771
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-02 13:58

I have a UserForm class:

class UserForm(Form):
    first_name = TextField(u\'First name\', [validators.Required()])
    last_name = TextField(u\'Last name\', [va         


        
6条回答
  •  我在风中等你
    2021-02-02 14:37

    I solved this by defining an additional __order attribute on my Form class, and overriding the __iter__ method so that the returned iterator's data is sorted first according to the definition. It might not be quite efficient, but there are not that many fields on a form, that it could cause any problem. It also works with fields from subclassed forms.

    class MyForm(Form):
        field3 = TextField()
        field1 = TextField()
        field2 = TextField()
    
        __order = ('field1', 'field2', 'field3')
    
        def __iter__(self):
            fields = list(super(MyForm, self).__iter__())
            get_field = lambda field_id: next((fld for fld in fields
                                               if fld.id == field_id))
            return (get_field(field_id) for field_id in self.__order)
    

提交回复
热议问题