1

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"))

Viktor
  • 79
  • 1
  • 8
  • With only flask I think you have to send the user to another page and flash( ) the message. – EdKenbers Jun 18 '20 at 17:07
  • @Ed.Kenbers, can't I show a message using Javascript or so? – Viktor Jun 18 '20 at 17:14
  • Yes it's possible with javascript see this [link] (https://stackoverflow.com/questions/40949746/how-to-display-flashing-message-without-reloading-the-page-in-flask) I think there is a solution there. – EdKenbers Jun 18 '20 at 17:20

1 Answers1

4

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.

Ken Kinder
  • 12,654
  • 6
  • 50
  • 70