You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建Python虚拟环境后出现jinja2.exceptions.TemplateNotFound错误如何解决

问题原因

你的错误是由主Python文件中render_template的参数填写错误导致的:

  1. 你初始化Flask实例时已经通过template_folder='html_scripts'指定了模板文件的存放文件夹为html_scripts,Flask会自动从该文件夹下查找模板,不需要再在render_template中重复传入文件夹名
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:15:01