使用Flask传递Python数据至HTML时遇TemplateNotFound错误求助
解决Flask模板找不到(TemplateNotFound: index.html)的问题
- 检查项目目录结构
Flask默认从项目根目录下的templates文件夹加载模板,你的项目必须遵循这个约定,正确结构示例:
你的项目文件夹/ main.py (你的Python脚本文件) templates/ index.html
如果templates文件夹不存在,直接创建;如果index.html和脚本同级,把它移到templates目录里。
核对模板文件名
确认index.html的文件名完全正确,注意大小写(Linux/macOS系统区分大小写,Index.html和index.html会被视为不同文件),避免多余空格或错误后缀。自定义模板路径(如果需要)
如果你的模板放在非默认路径,初始化Flask应用时可以显式指定模板目录:
from flask import Flask, render_template # 替换为你的模板文件夹实际路径,可以是绝对路径或相对路径 app = Flask(__name__, template_folder="./custom_templates") @app.route('/') def show_data(): # 这里是你查询数据库获取myresult的代码 return render_template('index.html', myresult=myresult)
- 检查render_template调用
确保返回时使用render_template('index.html', myresult=myresult),确认模板名称拼写正确,没有误写函数名(比如把render_template写成render_template_string)。
内容的提问来源于stack exchange,提问作者俠客行_da code learner
相关产品推荐
相关产品推荐

