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

Flask报错jinja2.exceptions.TemplateNotFound:无法找到index.html

Flask模板找不到问题解决办法

问题根源

你把app.py和模板文件一起放在了templates目录里,这不符合Flask的默认路径规则。Flask会自动在应用根目录下的templates文件夹中查找模板文件,当app.py在templates内部时,Flask会去templates/templates路径下找模板,自然找不到index.html。

正确目录结构

调整成以下结构:

你的项目文件夹/
├─ app.py
└─ templates/
   └─ index.html

解决步骤

  • 把app.py从templates目录移到项目根目录,index.html保留在templates内。
  • 确保render_template的调用只传入模板文件名,不要加完整路径:
    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return render_template('index.html')  # 只写文件名即可
    
    if __name__ == '__main__':
        app.run(debug=True)
    
  • 用IDLE运行时,确认当前工作目录是项目根目录(不是templates)。可以在app.py中加入以下代码验证:
    import os
    print("当前工作目录:", os.getcwd())
    
    如果输出不是项目根目录,手动切换到项目根目录后再运行脚本。

额外排查点

  • 检查templates文件夹的拼写,有没有少打s(比如写成template)。
  • 确认index.html文件名没有拼写错误,注意大小写(Windows下文件名不区分大小写,但最好保持一致)。

内容的提问来源于stack exchange,提问作者PythonUserLorenz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:42:33