wtforms Form class subclassing and field ordering

后端 未结 6 696
佛祖请我去吃肉
佛祖请我去吃肉 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:23

    To force an ordering on the form's fields you may use the following method:

    from collections import OrderedDict
    
    def order_fields(fields, order):
        return OrderedDict((k,fields[k]) for k in order)
    

    And call it within your forms constructor as follows:

    class FancyForm(Form, ParentClass1, ParentClass2...):
        x = TextField()
        y = TextField()
        z = TextField()
    
        _order = 'x y z'.split()
    
    
        def __init__(self, *args, **kwargs):
            super(FancyForm, self).__init__(*args, **kwargs)
            self._fields = order_fields(self._fields, 
                                        self._order + ParentClass1._order + ParentClass2._order)
    

提交回复
热议问题