0
0
FlaskDebug / FixBeginner · 3 min read

How to Fix Template Not Found Error in Flask

The TemplateNotFound error in Flask happens when Flask cannot find the HTML file in the templates folder. To fix it, ensure your template files are inside a folder named templates in your project root and use render_template('filename.html') with the correct filename.
🔍

Why This Happens

This error occurs because Flask looks for HTML files inside a folder named templates by default. If the folder is missing, misnamed, or the file path is wrong, Flask cannot find the template and raises TemplateNotFound.

python
from flask import Flask, render_template

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()
Output
jinja2.exceptions.TemplateNotFound: index.html
🔧

The Fix

Make sure you have a folder named templates in the same directory as your Flask app file. Put your index.html inside that folder. Flask will then find and render it correctly.

python
# Project structure:
# /your_project
#   app.py
#   /templates
#       index.html

from flask import Flask, render_template

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()
Output
The web page renders the content of index.html without errors.
🛡️

Prevention

Always keep your HTML templates inside a templates folder at the project root or the app root. Double-check filenames and spelling in render_template. Use consistent project structure and consider using an IDE or linter to catch missing files early.

⚠️

Related Errors

  • ImportError: Happens if Flask is not installed or imported incorrectly.
  • jinja2.exceptions.TemplateSyntaxError: Occurs if your HTML template has syntax mistakes.
  • FileNotFoundError: If static files like CSS or JS are missing, Flask may raise this.

Key Takeaways

Put all HTML templates inside a folder named 'templates' in your project root.
Use the exact filename in render_template, including the .html extension.
Check your project structure carefully to avoid path mistakes.
Use an IDE or linter to catch missing or misnamed template files early.
Related errors often involve missing imports or syntax mistakes in templates.