Implementing a simple static site from flask, but the browser says template not found, the shell returned 404
jinja2.exceptions.TemplateNotFound TemplateNotFound: template.html
The main python code:
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def template_test(): return render_template('template.html', my_string="Wheeeee!", my_list=[0,1,2,3,4,5]) if __name__ == '__main__': app.run(debug=True)
I have the following file structure:
flask_new_practice |--template/ |--template.html |--run.py
To fix Python Flask raising TemplateNotFound error even though template file exists, we can set the template_folder to the folder with the templates in our project. to set the template_folder argument to the path string relative to our project folder.
Flask looks for templates in the templates directory, which is called templates , so the name is important. Make sure you're inside the flask_app directory and run the following command to create the templates directory: mkdir templates.
render_template is a Flask function from the flask. templating package. render_template is used to generate output from a template file based on the Jinja2 engine that is found in the application's templates folder. Note that render_template is typically imported directly from the flask package instead of from flask.
To resolve the issue, simply create a folder name it “Templates”. Then move “index. html” into this newly created folder.
By default, Flask looks in the templates
folder in the root level of your app.
http://flask.pocoo.org/docs/0.10/api/
template_folder – the folder that contains the templates that should be used by the application. Defaults to 'templates' folder in the root path of the application.
So you have some options,
template
to templates
supply a template_folder
param to have your template
folder recognised by the flask app:
app = Flask(__name__, template_folder='template')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With