创建Python虚拟环境后出现jinja2.exceptions.TemplateNotFound错误如何解决
问题原因
你的错误是由主Python文件中render_template的参数填写错误导致的:
- 你初始化Flask实例时已经通过
template_folder='html_scripts'指定了模板文件的存放文件夹为html_scripts,Flask会自动从该文件夹下查找模板,不需要再在render_template中重复传入文件夹名 render_template需要传入具体的模板文件名,你传入了文件夹名html_scripts,自然触发模板找不到的错误。
解决方法
第一步:修正主Python文件代码
将两个视图函数的返回值修改为对应模板的文件名:
from flask import Flask, render_template app = Flask(__name__, template_folder='html_scripts') @app.route('/home/') def home(): # 对应html_scripts下的home_page.html return render_template('home_page.html') @app.route('/about/') def about(): # 对应html_scripts下的about.html return render_template('about.html') if __name__ == '__main__': app.run(debug = True)
第二步:确认项目目录结构正确
请确保你的项目目录和以下结构完全一致,避免路径拼写、文件位置错误:
项目根目录/ ├── 主运行文件(如app.py) ├── html_scripts/ │ ├── layout.html │ ├── home_page.html │ └── about.html └── static/ └── css/ └── main.css
可选检查项
如果修改后仍报错,可以做以下排查:
- 确认当前虚拟环境安装的Flask版本和此前运行正常的环境版本一致
- 确认所有模板文件的文件名、后缀名没有拼写错误
- 运行主Python文件时,确保当前工作目录为项目根目录,不要进入子目录后启动项目
内容的提问来源于stack exchange,提问作者codaKid
相关产品推荐
相关产品推荐

