Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用重定向(url_for)方法在Flask页面中显示消息?_Python_Html_Flask_Redirect_Render - Fatal编程技术网

Python 如何使用重定向(url_for)方法在Flask页面中显示消息?

Python 如何使用重定向(url_for)方法在Flask页面中显示消息?,python,html,flask,redirect,render,Python,Html,Flask,Redirect,Render,我有一个联系表单,用户可以在其中输入他的姓名、电话、电子邮件和反馈信息。按下submit按钮,我想在html页面中显示一条消息,通知他消息已经收到。如何做到这一点?我曾考虑将消息存储在会话中,但它没有显示在页面中。我无法呈现模板,因为在任何刷新时,都会再次发送消息。。。下面是我的代码: @app.route('/contact', methods=["POST", "GET"]) def contact(): if session.get("username") is not None:

我有一个联系表单,用户可以在其中输入他的姓名、电话、电子邮件和反馈信息。按下submit按钮,我想在html页面中显示一条消息,通知他消息已经收到。如何做到这一点?我曾考虑将消息存储在会话中,但它没有显示在页面中。我无法呈现模板,因为在任何刷新时,都会再次发送消息。。。下面是我的代码:

@app.route('/contact', methods=["POST", "GET"])
def contact():
    if session.get("username") is not None:
        email, password = edit_user(session["username"])
        session["error_message"] = " "

        if request.method == "POST":
            name = request.form["name"]
            phone = request.form["phone"]
            message = request.form["message"]
            result = send_email(email, name, message, phone) #method to check the form data and to actually send it
            if result == "Thank you for your message. We will get back to you shortly.":
                error_message = _("Thank you for your message. We will get back to you shortly.")
                session["error_message"] = error_message
                return redirect(url_for("contact"))
        return render_template("about/contact.html", error_message=session.get("error_message"), email=email)
    else:
        return redirect(url_for("login"))

你会喜欢你的闪光灯。实际上包括一个与您非常相似的示例:

@app.route'/login',methods=['GET','POST'] def登录: 错误=无 如果request.method==“POST”: 如果请求,则返回表单['username']!='管理员\ 请求。表单['password']!='秘密': 错误='无效凭据' 其他: flash“您已成功登录” 返回“索引”的重定向URL_ 返回render_模板'login.html',error=error 然后在模板中,您将迭代消息,向用户显示它们

{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

除非您正在使用SPA执行某些操作(这在您的代码示例中似乎不太可能),否则flask.flash是向用户传递消息的标准方式。

仅使用flask,我认为您必须将用户发送到另一个页面并刷新消息。@Ed.Kenbers,我不能用Javascript来显示消息吗?是的,用Javascript也可以看到这个[链接]我认为有一个解决方案。
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}