Forums

render_template not passing variables to template

Hello, all. I am having a weird issue with Flask's render_template function.

I had used Flask in the past for a basic project and I am just getting into it again. I have pulled my hair out since last night and I can not get this working. Thanks in advance for your guidance!

from flask import Flask, render_template

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

@app.route('/properties')
def properties():
     age = 45
     return render_template('properties_list.html', age=age)

I am using {{age}} in the properties_list.html page but the value never appears. If I try to use math on it (if less than), the page does not render and I get an error in the log that age is not defined. "jinja2.exceptions.UndefinedError: 'age' is undefined"

Have you reloaded your website (using the button on the "Web" page) after adding the age=age to the Python code? Changes to the Python site aren't picked up until you've reloaded. (Templates are automatically reloaded, however.)

Wow, that was it. How frustrating that was!

Can you explain why that is necessary though? I have app.config["DEBUG"] = True in the .py file and any HTML changes in the template seem to reload immediately. What are the rules?

PythonAnywhere doesn't reload anything by default -- you always need to reload the site -- but Flask has its own "auto-reload" behaviour for templates -- just not for Python code.

Django used to be the same, but they stopped automatically reloading templates a while back -- I think this was because (a) it was confusing when templates behaved differently to code in a production environment and (b) if you're editing a site, you often have to make changes in code and in templates, and it can cause problems if the template change goes live immediately, before the code changes are there to support it.

Sorry, I am still confused. Since I have "app.config["DEBUG"] = True", I thought any changes to .py and .html files would be automatically picked up once they are saved. This seems to work for a .py file but an .html file.

Setting DEBUG to true only changes the reload behaviour of Flask's test server -- not what it does when it's running in a production environment like PythonAnywhere.