I have been unable to get the flash function to work in flask. Heres my code.
#!venv/bin/python3
from flask import Flask, flash
app = Flask(__name__)
app.config['SECRET_KEY'] = '12345'
@app.route('/')
def index():
flash('Hi')
return 'Hello'
if __name__ == '__main__':
app.run()
I expected this to flash a message saying hi but when I load the page no flash box appears. What am I not understanding here?
I think the main problem is that you're returning a string and not a render_template that handles the flash and converts it to a display message. Check out this documentation code here for an example of how to handle flashes
So I suggest trying: return render_template('index.html')
And then use the index.html file to set up your code that handles the flash message. I have a feeling that just returning a string, as you've done here, without somewhere for the code to understand the flash will give a null result.
#!venv/bin/python3
from flask import Flask, flash, redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = '12345'
@app.route('/')
def index():
flash('Hi')
return redirect('index.html')
return render_template('index.html')
if __name__ == '__main__':
app.run()
ou can do following changes in your code import redirect and redirect it to any html page to show the flashed message.. in this case index.html and in index.html page you have to use jinja template to get flash message and display it in page for that we use get_flashed_messages()
In index.html file add following code
<body>
{% for mesg in get_flashed_messages() %}
<h1>{{ mesg }}</h1>
{% endfor %}
</body>
It has been a while since the question was asked. I'll post my answer here since I got to this question somehow.
As Miguel Grinberg wrote in "Flask Web Development: Developing Web Applications with Python":
Calling
flash()is not enough to get messages displayed; the templates used by the application need to render these messages.
So anyone who have the same problem, just ensure, that you added the get_flashed_messages() function to the template and then displayed a message. For the reference you can look at:
Python Flask flash not working correctly,
and for sure Miguel Grinberg's book mentioned above, Chapter 4.
Hope this will be helpful.