使用 WTForms model_form() 引发 UserForm has no attribute 'hidden_tag'

Using WTForms model_form() raises UserForm has no attribute 'hidden_tag'

我正在尝试在 WTForms 中使用 model_form 为给定模型自动生成 Form;但是,当我使用它时,出现以下错误:

UndefinedError: 'wtforms.ext.sqlalchemy.orm.UserForm object'
                 has no attribute 'hidden_tag'

我的代码如下所示:

from flask import Flask, render_template
from flask.ext.wtf import Form
from flask.ext.sqlalchemy import SQLAlchemy
from wtforms.ext.sqlalchemy.orm import model_form

app = Flask(__name__)
app.config.from_pyfile('app.cfg')
db = SQLAlchemy(app)

class User(db.Model):
    """Database model for SQLAlchemy."""
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)

UserForm = model_form(User, Form)

@app.route('/')
def index():
    """Show subscription form."""
    form = UserForm()
    return render_template('form.html', form=form)

并且在模板中:

<form class="register" action="{{ url_for('form_subscribe') }}" method="POST" >
{{ form.hidden_tag() }}

我检查了几个地方,包括 other questions 但我找不到合适的最佳实践解决方案。

显然 model_form 的参数顺序在版本 [1] [2] 之间发生了变化,因此它应该被称为:

UserForm = model_form(User, base_class=Form)

您也可以试试这个解决方案

from flask_wtf import FlaskForm
from wtforms_alchemy import model_form_factory

ModelForm = model_form_factory(FlaskForm)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)

class UserForm(ModelForm):
    class Meta:
        model = User