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

Flask模板加载报错:TemplateNotFound(patient_list2.html)求助

Flask 模板找不到错误分析

问题现象

这段代码无法运行,运行后抛出jinja2.exceptions.TemplateNotFound: patient_list2.html错误。

Python代码

from datetime import datetime, timedelta
import os
from flask import Flask, render_template
#import numpy as np
import pandas as pd

TEMPLATE_DIR = os.path.abspath('../templates')
STATIC_DIR = os.path.abspath('../static')

app = Flask(__name__, template_folder=TEMPLATE_DIR, static_folder=STATIC_DIR)

# datetime object containing current date and time
day = datetime.now()

print(f"now ={day}")

nomi = ['Mario', 'Gianluca', 'Nicola', 'Andrea', 'Simone']
date = []
date.append('Nomi')

for i in range(40):
    delta = timedelta(days=(i-(40/2)))
    append_day = day+delta
    displ_str = append_day.strftime("%d/%m/%Y")
    print(displ_str)
    date.append(displ_str)

df = pd.DataFrame(columns = date)
df['Nomi'] = nomi

@app.route('/', methods=("POST", "GET"))
def html_table():

    # link_column is the column that I want to add a button to
    return render_template("patient_list2.html", column_names=df.columns.values, 
row_data=list(df.values.tolist()), link_column="Patient ID", zip=zip)



if __name__ == '__main__':
    app.run(host='0.0.0.0')

HTML代码

<head>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document with python</title>
     <link href="{{ url_for('static', filename='css/patient_list.css') }}" 
     rel="stylesheet" type="text/css" >
 </head>
 <body>
     <table>
         <tr>
             {% for col in column_names %}
             <th>{{col}}</th>
             {% endfor %}
         </tr>
         {% for row in row_data %}
         <tr>
             {% for col, row_ in zip(column_names, row) %}
             {% if col == link_column %}
             <td>
                <button type="submit" value={{ row_ }} name="person_id" 
 form="patient_form" class="patient_button">
                {{ row_ }}
            </button>
        </td>
        {% else %}
        <td>{{row_}}</td>
        {% endif %}
        {% endfor %}
    </tr>
    {% endfor %}

   </table>
</body>

CSS代码

table{
display: flex;
border: 2px solid darkblue;
font-size: medium;
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
overflow-x: auto;
}

td, th {
border: 1px solid #121111;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #d6e0ee;
}

tr:first-child {
background-color: yellowgreen;
}

运行错误信息

[2024-08-20 12:00:15,876] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\flask\app.py", line 1473, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\flask\app.py", line 882, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\flask\app.py", line 880, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\flask\app.py", line 865, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\showTable.py", line 35, in html_table
    return render_template("patient_list2.html", column_names=df.columns.values, row_data=list(df.values.tolist()), link_column="Patient ID", zip=zip)
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\flask\templating.py", line 149, in render_template
    template = app.jinja_env.get_or_select_template(template_name_or_list)
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\jinja2\environment.py", line 1084, in get_or_select_template
    return self.get_template(template_name_or_list, parent, globals)
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\jinja2\environment.py", line 1013, in get_template
    return self._load_template(name, globals)
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\jinja2\environment.py", line 972, in _load_template
    template = self.loader.load(self, name, self.make_globals(globals))
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\jinja2\loaders.py", line 126, in load
    source, filename, uptodate = self.get_source(environment, name)
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\flask\templating.py", line 65, in get_source
    return self._get_source_fast(environment, template)
  File "C:\Users\mnardo\Desktop\Pers\Flask_Prj\hello_flask\venv\lib\site-packages\flask\templating.py", line 99, in _get_source_fast
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: patient_list2.html
127.0.0.1 - - [20/Aug/2024 12:00:15] "GET / HTTP/1.1" 500 -

错误原因分析

这个错误的核心是Flask找不到指定的模板文件patient_list2.html,可能的原因包括:

  • 模板路径配置错误:代码中设置的模板目录是../templates(上级目录下的templates文件夹),但实际项目结构可能不匹配。比如Python脚本showTable.py在hello_flask目录下,../templates会指向Flask_Prj/templates,但如果模板实际在hello_flask/templates下,路径就会出错。
  • 文件名不匹配:检查模板文件实际文件名是否为patient_list2.html,注意大小写(Linux/macOS区分大小写)、拼写错误或后缀错误。
  • 模板目录不存在:确认../templates目录是否真实存在,目录不存在的话Flask无法加载模板。
  • 路径计算错误:os.path.abspath('../templates')的计算结果可能不符合预期,可以打印该路径确认是否指向正确的模板文件夹。

修复建议

  1. 打印TEMPLATE_DIR的实际路径,验证是否指向正确的模板文件夹:
    print(TEMPLATE_DIR)
    
  2. 调整模板目录路径为正确的相对路径,比如脚本和templates文件夹同级时,改为os.path.abspath('templates')。
  3. 确认patient_list2.html文件确实存在于指定的templates目录下,文件名完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:10:57