Srdjan Ristic Srdjan Ristic - 2 months ago 26
Python Question

Flask raises TemplateNotFound error even though template file exists

I am trying to render the file

home.html
. The file exists in my project, but I keep getting
jinja2.exceptions.TemplateNotFound: home.html
when I try to render it. Why can't Flask find my template?

from flask import Flask, render_template

app = Flask(__name__)

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




/myproject
app.py
home.html

Answer

You must create your template files in the correct location; in the templates subdirectory next to your python module.

The error indicates that there is no home.html file in the templates/ directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a home.html file in that subdirectory. If your app is a package, the templates folder should be created inside the package.

myproject/
    app.py
    templates/
        home.html
myproject/
    mypackage/
        __init__.py
        templates/
            home.html

Alternatively, if you named your templates folder something other than templates and don't want to rename it to the default, you can tell Flask to use that other directory.

app = Flask(__name__, template_folder='template')  # still relative to module