初学Python Flask框架,遇到问题绕了半天,求解答
先上代码,这个是 routing 和 view
@auth.route('/change-password', methods=['GET', 'POST'])
[@login_required](/user/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)
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)
这个是 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 %}%
这个是各个模板的父模板 base.html 中的相关部分
<li><a href="{{ url_for('auth.change_password') }}">Change Password</a></li>
上面实现的功能是,已登录用户如果点击 Change Password,链接就会跳转到 /change-password,跳出一个重置密码的表单,点完提交按钮后,application 然后再执行对应的 view function。
我的问题是:当点击 Change Password 后,跳转到 /change-password 地址后,会展现一个重置密码的表单,我没理解的地方是,按照路由映射关系,/change-password 这个 url 交由 change_password()这个视图处理,按照函数执行的顺序,先引用表单即 form=ChangePasswordForm(),然后更新密码,最后返回一个重定向到主页,就结束了。这样的话,那么return render_template("auth/change_password.html", form=form)这段代码压根就没执行到,都没有返回渲染后的模板文件,又怎么有了前面点击 chang password 就蹦出一个重置密码表单的页面呢?
这里我给绕晕了,求解释下,谢谢大家
初学Python Flask框架,遇到问题绕了半天,求解答
点了 submit 才会重定向到 index,没点就显示这个页面,注意有个 if。
我无法理解你的问题
你点击 chang_password 时是一个 get 请求,所以 if 那块的代码根本不会执行,执行的只是 render_template 那块的代码,想看到底执行没执行打个断点看看,就明白了
点击 submit 后才会跳转到 index 不然渲染的是 change passwd 页面呀
if form.validate_on_submit()
感谢
厉害了 一阵见血
thx
thx
恩 知道了 thx !


