python - 重定向(url_for())传递参数不起作用
问题描述
当我使用重定向和 url_for 传递参数时,它会将它们添加到 url 但不会在 html 中显示它们。如果我使用 render_template 并传递参数,它就可以正常工作。
我的代码:
@app.route("/forgotpass", methods = ["GET", "POST"])
def forgot_password():
if session["logged_in"] == True:
return redirect(url_for("profile"))
if request.method == "POST":
email = request.form["username"]
email = email.lower()
logins.forgotPassword(email)
return redirect(url_for("login", error = "We have sent you an email with your new password!"))
elif request.method == "GET":
return render_template("forgotPassword.html")
HTML:
<p>{{ error | default('') }}</p>
有谁知道我该如何解决?
解决方案
这就是url_for
工作原理,您可以将参数/变量传递给它,这些参数/变量将被添加到 URL 中,它不是为了显示错误而制作的。
如果您想向用户显示消息,例如在成功登录或登录失败时,您应该使用消息闪烁代替:https ://flask.palletsprojects.com/en/1.1.x/patterns/flashing/
示例代码,flash
先从flask导入:
@app.route("/forgotpass", methods = ["GET", "POST"])
def forgot_password():
if session["logged_in"] == True:
return redirect(url_for("profile"))
if request.method == "POST":
email = request.form["username"]
email = email.lower()
logins.forgotPassword(email)
flash('We have sent you an email with your new password!')
return redirect(url_for("login"))
elif request.method == "GET":
return render_template("forgotPassword.html")
将其放在您的登录模板中的某个位置:
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
推荐阅读
- python - 从 yaml 中提取不同的值
- html - 如何在表中显示组(上面的 Angular 6)
- reactjs - 如何在reactjs中有条件地隐藏和显示?
- javascript - javascript Proper Tail Recursion 是如何实际实现的?
- java - 指定合作伙伴(来自 CCC 竞赛)
- asp.net-mvc - dropzone 和 asp.net core 3.1 - 发送到控制器的正确参数是什么?
- sql-server - 存储过程更新以删除重复项
- scala - 为什么 Some(1).toString 在scala中不等于“1”?
- android - 如何在 android 上获取 MediaFormat 的 csd-0
- terminal - emacsclient,在终端中恢复一个框架中的所有窗口