pythonhtmlflaskflashjinja2

Jinja Code coming up as text from Flask to HTML webpage


I have been attempting to flash a simple message to a webpage via Flask and Jinja, and yet it always reuslts in the jinja code being displayed as simple text.

Here is my app.py code:

from flask import Flask, flash, redirect, render_template

app = Flask(__name__)
app.config['SECRET_KEY'] = '12345'

@app.route('/')
def index():
    flash('Hello, this is a flash message!')
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

Here is my index.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flash Message Example</title>
</head>
<body>
    {% for mesg in get_flashed_messages() %}
        <h1>{{ mesg }}</h1>
    {% endfor %}
</body>
</html>

My directory structure is very simple:

directory structure

I have tried almost everything, looked and adpated multiple tutorials, simplified the program to its skeleton, uninstalled and re-installed Flask, but still the Jinja Code comes up as text like so: display

What am I missing here?


Solution

  • Your code is fine, everything is set up correctly. It appears that you are manually opening your index.html file in the browser (i.e., double-clicking index.html). For your page to display correctly, you need to start your server and then navigate to the home route to see the correct page.

    Start the server:

    python app.py

    You should get some output like this:

     * Serving Flask app 'app'
     * Debug mode: on
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
     * Running on http://127.0.0.1:5000
    Press CTRL+C to quit
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: xxx-xxx-xxx
    

    Then, open your browser and navigate to http://127.0.0.1:5000. The page should display correctly.