简体   繁体   中英

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. 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. How do achieve this? I was thinking of storing the message in a session, but it doesn't get displayed in the page. 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM