Flask项目模板找不到错误求助:jinja2.exceptions.TemplateNotFound
解决Flask中
jinja2.exceptions.TemplateNotFound错误 首先先确认你的项目结构应该是这样的对吧:
FlaskUserAuthentication/ ├── FlaskUserAuthentication/ │ ├── __init__.py │ ├── API/ │ │ ├── __init__.py │ │ └── routes.py │ └── Site/ │ ├── __init__.py │ ├── routes.py │ └── templates/ │ └── Site/ │ ├── index.html │ └── login.html └── run.py
问题出在你的Blueprint模板路径配置和实际模板存放位置不匹配:
你给Site这个Blueprint设置了template_folder='templates',这会让Flask去Site/templates/目录下找模板文件,但你的index.html和login.html其实是在Site/templates/Site/这个子目录里,所以直接用render_template('index.html')自然找不到。
这里有两种简单的解决方法:
方法一:修改render_template的路径
直接在渲染模板时加上子目录的路径,让Flask能定位到正确的文件:
from flask import Blueprint, render_template site = Blueprint('Site', __name__, template_folder='templates') @site.route('/index') def index(): return render_template('Site/index.html') # 加上Site子目录 @site.route('/login') def login(): return render_template('Site/login.html') # 同样加上子目录
方法二:调整Blueprint的template_folder路径
把Blueprint的模板目录直接指向实际存放模板的Site/templates/Site,这样就可以直接用模板文件名了:
from flask import Blueprint, render_template # 直接将模板目录设置为templates/Site site = Blueprint('Site', __name__, template_folder='templates/Site') @site.route('/index') def index(): return render_template('index.html') @site.route('/login') def login(): return render_template('login.html')
另外也可以检查一下模板文件名和路径的拼写,尤其是大小写——在Linux或macOS系统里,路径和文件名是区分大小写的,如果你的实际文件名是Index.html但代码里写的是index.html也会导致找不到的问题。
内容的提问来源于stack exchange,提问作者Natasha




