使用WTForms model_form()引发UserForm没有属性'hidden_​​tag'

时间:2015-11-18 18:23:17

标签: python flask sqlalchemy wtforms flask-wtforms

我正在尝试在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,但我找不到合适的最佳做法解决方案。

2 个答案:

答案 0 :(得分:2)

显然model_form的论据顺序在版本[1] [2]之间发生了变化,所以它应该被称为:

UserForm = model_form(User, base_class=Form)

答案 1 :(得分:0)

您也可以尝试此解决方案

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