wtforms Form class subclassing and field ordering

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

    This is how I accomplish what were you trying to do:

    class UserForm(wtforms.Form):                                                   
        def __init__(self, *args, **kwargs):                                        
            super(UserForm,self).__init__(*args, **kwargs)                          
    
            if kwargs.get('update', None):                                          
                self['passwd'].validators.append(wtforms.validators.Optional())
                self['passwd'].flags.required = False     
            else:                                                                   
                self['passwd'].validators.append(wtforms.validators.Required()) 
    
        passwd = UnicodeField(                                                      
            u'Password',                                                            
            [                                                                       
                wtforms.validators.length(max=50),                                  
                wtforms.validators.EqualTo(                                         
                    'confirm',                                                      
                    message='Passwords must match'                                  
                    )                                                               
                ],                                                                  
            widget = wtforms.widgets.PasswordInput()                                
            )                                                                       
    
        confirm = wtforms.PasswordField(u'Password Verify')
    

    Then, when I instantiate the UserForm, I pass update=True when editing. This appears to work for me.

提交回复
热议问题