[英]How to show a message in a Flask page using redirect(url_for) method?
I have a contact form, where the user gets to enter his name, phone, email and a feedback message.我有一个联系表格,用户可以在其中输入他的姓名、电话、email 和反馈消息。 At the push of the submit button, I want to show a message in the html page, to inform him that the message has been recieved.
按下提交按钮后,我想在 html 页面显示一条消息,通知他消息已收到。 How do achieve this?
如何做到这一点? I was thinking of storing the message in a session, but it doesn't get displayed in the page.
我正在考虑将消息存储在 session 中,但它没有显示在页面中。 I cannot render the template, because so, at any refresh, the message gets sent again... below is my code:
我无法呈现模板,因为因此,在任何刷新时,消息都会再次发送......下面是我的代码:
@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"))
You would you flask.flash
.你会
flask.flash
。 The documentation actually includes an example very similar to yours:该 文档实际上包含一个与您的非常相似的示例:
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'secret':
error = 'Invalid credentials'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error)
Then in your templates, you would iterate over the messages, showing them to the user.然后在您的模板中,您将遍历消息,将它们显示给用户。
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
Unless you're doing something with an SPA, which doesn't seem likely given your code example, flask.flash
is the canonical way of passing messages to the user.除非您使用 SPA 做某事,否则在您的代码示例中这似乎不太可能,
flask.flash
是将消息传递给用户的规范方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.