【问题标题】:WTForms: Creating an edit profile form that ensures the password is the valid password for the user?WTForms:创建一个编辑配置文件表单以确保密码是用户的有效密码?
【发布时间】:2022-10-05 05:35:54
【问题描述】:

在我的类似推特的应用程序中,我希望允许用户编辑他们的个人资料。如果用户在编辑表单中提交的密码不是有效密码,我的应用程序应该闪烁一条消息(“密码错误”)并重定向到主页。

我遇到的问题是确保提交的密码是有效密码的表单。这是我到目前为止所拥有的:

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.') 

我从另一篇文章中找到了这个验证器方法,但我不知道如何正确初始化表单(未定义“用户”):

@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()  

如果有人有另一种解决方案来确保密码是正确的密码,或者可以指出我如何滥用上述内容,我将不胜感激!

【问题讨论】:

    标签: python methods passwords flask-wtforms


    【解决方案1】:

    对验证器执行此操作:

    def validate_password(self, password):
        if password.data != get_user_byEmail(self.email.data):
            raise ValidationError('Wrong password.')
    

    当然你必须实现 get_user_by Email(email: string)

    在路由中将表单传递给模板

    return render_template('templateName')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2010-09-22
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多