wtforms Form class subclassing and field ordering

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

    In regards to your first question about reording the fields when iterating over the form object, this is what I did:

    class BaseForm(Form):
        def __iter__(self):
            field_order = getattr(self, 'field_order', None)
            if field_order:
                temp_fields = []
                for name in field_order:
                    if name == '*':
                        temp_fields.extend([f for f in self._unbound_fields if f[0] not in field_order])
                    else:
                        temp_fields.append([f for f in self._unbound_fields if f[0] == name][0])
                self._unbound_fields = temp_fields
            return super(BaseForm, self).__iter__()
    
    class BaseUserForm(BaseForm):
        password = PasswordField('Password', [Required()])
        full_name = TextField('Full name', [Required()])
    
    class NewUserForm(BaseUserForm):
        username = Textfield('Username', [Required()])
        field_order = ('username', '*')
    

    That way, when you render NewUserForm (perhaps from a template which iterates over the form rendering field by field), you'll see username, password, full_name. Normally you'd see username last.

提交回复
热议问题