1

When I hit refresh on a page with flash message already showing, the message persist even after the refresh. How do I stop the message from showing on refresh? I noticed when I use render_template after flash the flash message will persist, but when I use redirect it doesn't. However I have to pass a non-3xx status code when I flash a message, using redirect only gets user wait on a redirection page until further action, which is not desirable either.

Method 1: Shows the right page but message persists on refresh:

flash("An error occurred.")
return render_template("page.html"), 400

Method 2: Stuck on redirection page but message doesn't persist on refresh:

flash("An error occurred.")
return redirect(url_for('show-page'), code=400)

Redirecting... You should be redirected automatically to target URL: /page. If not click the link.

Method 2 does work as I intended if I pass a 3xx code, but I need to pass non-3xx code.

Note: The user should be on the same page throughout.

liyche
  • 21
  • 4
  • Could you add the page.html and show-page method, and also the page where you are getting and displaying the flashed messages. – viggnah Jul 08 '22 at 04:27
  • @viggah page.html contains a form and I flash an error message after user submits invalid info with the form, so page.html also displays the flash message. I decided to go with method 2 with a 3xx code. – liyche Jul 08 '22 at 17:53

2 Answers2

1

In my case, the flash message pops up to give users feedback immediately after they submit a form. The message persisted after refresh because the refresh triggered a double submit of the form. Redirect prevents the double submit problem and subsequently the persistent message. I read another post on the status code. Since this is all user-facing rather than a REST API, status code doesn't really matter, I went with method 2 with a 3xx default status code:

flash("An error occurred.")
return redirect(url_for('show-page'))
liyche
  • 21
  • 4
0

In my case all the messages were stuck in session when using the stream_template and when changing to render_template the messages were removed from the session normally.

@app.route("/startpage", methods=['GET', 'POST'])
def startpage():
    if validate_token() == True:
        flashes = session.get('_flashes', [])
        print(flashes)
        #return stream_template('start_page.html', title="Inicio")
        return render_template('start_page.html', title="Inicio")
    else:
        return redirect(url_for('index'))

I did some tests and in my case it really was that. I didn't find anything in the Flask documentation talking about this difference in stream_template and render_template.