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

Flask Blueprint初始化报错:意外关键字参数'template_folder'

Flask项目报错解决:TypeError: Blueprint.init() got an unexpected keyword argument 'template_folder'

项目目录结构

p/
   student/
      template/
          student/
              index.html
      views.py
   __init__.py
app.py

各文件内容

app.py

from flask import Flask, render_template
from p import app

@app.route("/")
def index():
    return render_template("index.html")
if __name__ == "__main__":
    app.run()

p/init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://postgres:1234@localhost/studentRegDB"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)
Migrate(app, db)

from p.student.views import student_blueprints
app.register_blueprint(student_blueprints, url_prefix='/student')

p/student/views.py

from flask import Flask, request
import psycopg2
from p import db
from p.student.forms import studentform
from p.student.models import Student
from flask import render_template, url_for,redirect
from flask_blueprint import Blueprint  # 错误导入
student_blueprints = Blueprint('student', __name__, template_folder='student')

@student_blueprints.route("/add", methods=["GET", "POST"])
def addstudent():
    form = studentform()
    if form.validate_on_submit():
        name = request.form['name']
        course = request.form['course']
        new_student = Student(name,course)
        db.session.add(new_student)
        db.session.commit()
        return redirect(url_for("success.html"))
    return render_template("student.html", form=form)

报错信息

student_blueprints = Blueprint('student', __name__, template_folder='student')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Blueprint.__init__() got an unexpected keyword argument 'template_folder'

解决方法

1. 修正Blueprint的导入语句

你错误地从第三方包flask_blueprint导入了Blueprint,而Flask原生的Blueprint组件是内置在flask模块中的。把views.py里的导入语句改成:

from flask import Blueprint

2. 调整template_folder路径(适配目录结构)

根据你的目录结构,模板文件存放在p/student/template/student/下,所以Blueprint的template_folder应该指向template目录,确保Flask能正确找到模板:

student_blueprints = Blueprint('student', __name__, template_folder='template')

之后调用render_template时,可直接写对应模板的路径,比如render_template("student/index.html")。

3. 修正redirect的url_for用法

代码里redirect(url_for("success.html"))是错误的,url_for需要传入视图函数名而非模板文件名。如果有一个名为success的视图函数,应写成redirect(url_for("student.success"))(若success属于student蓝图),或者直接用redirect("/success")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:55:28