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

Flask应用模板路径错误:解决jinja2.TemplateNotFound问题

问题解决:jinja2.exceptions.TemplateNotFound: index.html

错误原因

你在render_template函数中传入template_folder='flasktemp'是错误的——这个参数不属于render_template,而是创建Flask应用实例时的配置项。Flask默认会在应用根目录下的templates文件夹查找模板,你的模板存放在flasktemp目录,因此需要正确配置模板路径。

解决方案

方法1:修改Flask实例初始化代码(推荐)

在创建Flask应用时指定template_folder参数,指向你的模板目录,同时移除render_template中的无效参数:

from flask import Flask, render_template, request
import os

# 初始化Flask时指定模板目录为flasktemp
app = Flask(__name__, template_folder='flasktemp')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        json_files_initial = request.files.getlist('json_file_desc2')
        save_directory_initial = 'D:/../../../descriptors_2'
        for json_file_initial in json_files_initial:
            if json_file_initial:
                json_filename_initial = json_file_initial.filename
                json_file_initial.save(os.path.join(save_directory_initial, json_filename_initial))

        generate_info_txt = request.form.get('generate_info_txt')

        if generate_info_txt == 'yes':
            json_files_latter = request.files.getlist('json_file_desc3')
            save_directory_latter = 'D:/../../../descriptors_3'
            for json_file_latter in json_files_latter:
                if json_file_latter:
                    json_filename_latter = json_file_latter.filename
                    json_file_latter.save(os.path.join(save_directory_latter, json_filename_latter))

        # os.system('python path/to/nocodegen-test.py')
        return "Files saved and script executed successfully!"

    # 直接传入模板文件名即可
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

方法2:调整目录结构为Flask默认规则

将src/flasktemp文件夹重命名为src/templates,这样无需额外配置,保持原代码中app = Flask(__name__)和render_template('index.html')即可,Flask会自动识别默认的templates目录。

原理说明

Flask应用初始化时的template_folder参数用于指定模板文件的存放路径,路径是相对于应用根目录(即app.py所在的src目录)的。render_template函数仅需传入模板文件名,Flask会自动到配置好的模板目录中查找对应文件。

内容的提问来源于stack exchange,提问作者Mohammed Saim Quadri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:22:23