首页 > 解决方案 > 重定向(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>

有谁知道我该如何解决?

标签: pythonflask

解决方案


这就是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 %}

推荐阅读