Flask WTForms w / SQLAlchemy:将表单存储在数据库中时出现UnmappedInstanceError

时间:2014-05-07 03:01:46

标签: flask sqlalchemy flask-sqlalchemy wtforms flask-wtforms

我无法使用Flask-SQLAlchemy将表单存储在 sqlite3 数据库中。当我尝试存储表单时,我的views.py会抛出以下错误。

UnmappedInstanceError: Class 'app.forms.Survey1' is not mapped

Views.py

@app.route('/survey_1/', methods=['GET','POST'])
@login_required
def survey_1():
    form = Survey1(request.form)
    if form.validate_on_submit():
        print form
    db.session.add(form)
    db.session.commit()
    return redirect(url_for('index'))
    return render_template('Survey1.html', title='Survey', form=form)

Models.py

class Survey1(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    gender = db.Column(db.Integer)
    age = db.Column(db.Integer)
    education = db.Column(db.Integer)
    language = db.Column(db.String(20))
    db = db.relationship('Database', backref='survey1', lazy='dynamic')

    def __init__(self, gender=None, age=None, education=None, language=None):
        self.gender=gender
        self.age=age
        self.education=education
        self.language=language

    def get_id(self):
        return unicode(self.id)

Forms.py

class Survey1(Form):
    gender=fields.RadioField('X', choices=[('Y','Y'),('Z','Z')],validators = [Required()])
    age=fields.RadioField('X', choices=[('Y','Y'),('Z','Z')], validators=[Required()])
    education = fields.RadioField('X',choices=[('Y','Y'),('Z','Z')],validators=[Required()])
    language = fields.TextField('Native Language', validators=[Required()])

如何存储此表单?

1 个答案:

答案 0 :(得分:3)

SQLAlchemy的方法仅适用于SQLAlchemy对象 - 您的问题是您传递的是WTForms Form类的实例(SQLAlchemy不知道如何持久保存到您的数据库)。一旦更改Form声明以匹配Model类中的类型({{{}},就可以使用Form.populate_obj从WTForms类映射到您的SQLAlchemy对象1}},genderage都在education课程中标记为Integer,但Model课程中的String字段均为Form个字段)。

if form.validate_on_submit():
    model = models.Survey1()

    form.populate_obj(model)

    db.session.add(model)
    db.session.commit()
    return redirect(url_for('index'))