close

How to display flashing message without reloading the page in Flask?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to display flashing message without reloading the page in Flask in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to display flashing message without reloading the page in Flask?

  1. How to display flashing message without reloading the page in Flask?

    This is not possible via Python without reloading the page. You must do this in javascript. I suggest CSS styling with display: none and display: block.

  2. display flashing message without reloading the page in Flask

    This is not possible via Python without reloading the page. You must do this in javascript. I suggest CSS styling with display: none and display: block.

Method 1

This is not possible via Python without reloading the page. You must do this in javascript. I suggest CSS styling with display: none and display: block. Here is an example.

1) Python Code, this should go in your app.py or flask.py file.

app.route('/flash/<message>')
def flash(message):
  return render_template('flash.html', msg=message)

This will render the HTML page named flash.html. The URL passed in will also have another argument, <message> this is the message that will flash. A URL like this, localhost:80/flash/Hello%20World! will flash the message “Hello World!” on your screen.

There is also another way to pass a message in, this is will arguments. The code for that is like so.

app.route('/flash')
def flash():
  message = request.args.get("msg")
  return render_template("flash.html", ,msg=message)

This uses the flask’s request arguments. So a URL like this, localhost:80/flash?msg=Hello%20World! will give a flashing message saying “Hello World!”. If you want to use this method be sure to have the import statement, from flask import request in your import statements.

2) Html Code, this is a separate file named, flash.html in your templates folder.

<body>
  <h1 id="header">{{ message }}</h1>
  <script>
    var heading = $("#header");
    setInterval(function() {
      if (heading.style.display == "block") { heading.style.display = "none"; }
      else if (heading.style.display == "none") { heading.style.display = "block"; }
    }, 1000);
  </script>
</body>

The 1000 in the setInterval is milliseconds. So the heading will blink every 2 seconds.

Method 2

You may want to consider using Toastr instead. I ran into the same roadblock with Flask’s Flash feature, and Toastr is pure JS. You can use it just like a console log line in your code

toastr.info("Here's a message to briefly show to your user");

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read