Search code examples
pythonflaskflask-sqlalchemyflask-wtformsflask-security

Python Flask wt forms ventilator check if password is matching database


I am trying to create a from where before updating records the user must type in their password for validation.

I was thinking of useing something like this.

class AccountSettingsForm(Form):
        password_proof= TextField("Password:",[validators.EqualTo(current_user.password, message='Passwords Invlaid')])

But i get this error
AttributeError: 'NoneType' object has no attribute 'password'


Solution

  • You need to create a validator method with the syntax validate_{field_name}. Also, as you are using other data (the user instance, which contains their password), you need to initialize the form with that user instance.

    Something like this should work for your example:

    from wtforms import ValidationError
    
    class AccountSettingsForm(Form):
        password_proof= TextField("Password:")
    
        def __init__(self, user, *args, **kwargs):
            super(AccountSettingsForm, self).__init__(*args, **kwargs)
            self.user = user
    
        def validate_password_proof(self, field):
            if field.data != self.user.password:
                raise ValidationError('Wrong password.')
    

    Then, when initializing the form, you need to do it like this:

    form = AccountSettingsForm(current_user)
    

    On an unrelated side note, you should encrypt your users' passwords if you are not doing so.