In my twitter-like app, I want to allow users to edit their profiles. If the password the user submits in the edit form is not the valid password, my app should flash a message ("Wrong password") and redirect to the homepage.
What I'm having trouble with is the form ensuring that the submitted password is the valid password. Here's what I have so far:
class EditProfileForm(FlaskForm):
"""Edit form"""
username = StringField('Username', validators=[DataRequired()])
email = StringField('E-mail', validators=[DataRequired(), Email()])
image_url = StringField('(Optional) Image URL')
header_image_url = StringField('(Optional) Image URL')
bio = StringField('(Optional) Bio')
password = PasswordField('Password')
def __init__(self, user, *args, **kwargs):
super(EditProfileForm, self).__init__(*args, **kwargs)
self.user = user
def validate_password_proof(self, field):
if form.data != self.user.password:
raise ValidationError('Wrong password.')
I found this validator method from another post, but I can't figure out how to properly initialize the form ('user' is not defined):
@app.route('/users/profile', methods=["GET", "POST"])
def profile():
"""Update profile for current user."""
if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")
form = EditProfileForm(user)
return render_template()
If anyone has another solution to ensure the password is the correct password or can point out how I'm misusing the above I'd appreciate it!
Do this to the validator:
def validate_password(self, password):
if password.data != get_user_byEmail(self.email.data):
raise ValidationError('Wrong password.')
of course you have to implement get_user_byEmail(email: str)
in the route pass the form to the template
return render_template('templateName')