修改密码:修改密码只需要用户处于登录状态,就可以放心显示一个表单,要求用户输入旧密码和替换的新密码。通过导航栏的 Change Password可以键入密码修改界面。
1. templates/auth/change_password.html:修改密码模板
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky - Change Password{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Change Your Password</h1>
</div>
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
{% endblock %}
2. auth/forms.py:修改密码用到的表单
class ChangePasswordForm(FlaskForm):
old_password = PasswordField('Old password', validators=[DataRequired()])
password = PasswordField('New password', validators=[
DataRequired(), EqualTo('password2', message='password must match')])
password2 = PasswordField('Confirm new password', validators=[DataRequired()])
submit = SubmitField('Update Password')
3. auth/views.py:修改密码视图处理函数
@auth.route('/change-password', methods=['GET', 'POST'])
@login_required
def change_password():
form = ChangePasswordForm()
if form.validate_on_submit():
if current_user.verify_password(form.old_password.data):
current_user.password = form.password.data
db.session.add(current_user)
db.session.commit()
flash('Your password has been updated.')
return redirect(url_for('main.index'))
else:
flash('Invalid password.')
return render_template('auth/change_password.html', form=form)
4.测试过程: