Home > Software design >  Flask simple render_template implementation fails
Flask simple render_template implementation fails

Time:10-16

I’m trying to make a flask site and so far it’s working to print a hello world. When I try and turn from outputting text to outputting a simple html template the site breaks and I get the error below.

This is my code:

from flask import render_template, Blueprint

recipes_blueprint = Blueprint('recipes', __name__, template_folder='templates')

@recipes_blueprint.route('/')
def index():
     return    
render_template('list.html')

And my list.html is simply the below inside the templates folder:

<h1>Test</h1>

The full error is here:

2021-10-16 07:50:53,399:     from app import app as application  # noqa
2021-10-16 07:50:53,399: 
2021-10-16 07:50:53,399:   File "/home/jameshiven/mysite/app.py", line 3, in <module>
2021-10-16 07:50:53,399:     from products.views import products_bp
2021-10-16 07:50:53,399: 
2021-10-16 07:50:53,399:   File "/home/jameshiven/mysite/products/views.py", line 12, in <module>
2021-10-16 07:50:53,399:     render_template('list.html')
2021-10-16 07:50:53,399: 
2021-10-16 07:50:53,399:   File "/usr/local/lib/python3.9/site-packages/flask/templating.py", line 146, in render_template
2021-10-16 07:50:53,399:     ctx.app.update_template_context(context)
2021-10-16 07:50:53,400: 

CodePudding user response:

Blueprints are supossed to be registered with flask app to be appeared in the app.

Modify your code to

from flask import render_template, Blueprint, Flask

recipes_blueprint = Blueprint('recipes', __name__, template_folder='templates')
app = Flask(__name__)
app.register_blueprint(recipes_blueprint)

@app.route('/')
def index():
    return render_template('list.html')

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

Some examples here, here

CodePudding user response:

You didn't provide the actual exception message, but I'm going to guess it was:

AttributeError: 'NoneType' object has no attribute 'app'

This is because your view function is messed up. Change it to say:

@recipes_blueprint.route('/')
def index():
    return render_template('list.html')

Then register your blueprint with the app object like John suggested.

  • Related