【问题标题】:Flask WTForms w/ SQLAlchemy: UnmappedInstanceError when storing a form in a database带有 SQLAlchemy 的 Flask WTForms:在数据库中存储表单时出现 UnmappedInstanceError
【发布时间】:2014-06-23 20:25:42
【问题描述】:

我无法使用 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)

模型.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()])

如何存储此表单?

【问题讨论】:

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


    【解决方案1】:

    SQLAlchemy 的方法仅适用于 SQLAlchemy 对象 - 您的问题是您正在传递 WTForms Form 类的实例(SQLAlchemy 不知道如何持久保存到您的数据库)。一旦您更改 Form 声明以匹配 Model 类中的类型(genderage、和educationModel 类中都标记为Integer,但在Form 类中是String 字段)。

    if form.validate_on_submit():
        model = models.Survey1()
    
        form.populate_obj(model)
    
        db.session.add(model)
        db.session.commit()
        return redirect(url_for('index'))
    

    【讨论】:

    • 首先感谢您的回复,我知道根本问题出在哪里。我希望您能详细说明models.Survey1(),我不明白这是如何将WTForm obj 映射到SQLAlchemy obj 的。此外,单选按钮是否总是存储为字符串,因为我相信它也可以是整数。
    • 实际上是form.populate_objform 中的数据映射到空的model。对于应该是整数的表单字段,您可以使用 coerce=int 作为字段构造函数的参数:fields.RadioField("An integer field", coerce=int, choices=[...])
    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 2015-12-12
    • 2021-07-02
    • 2019-05-04
    • 2018-02-09
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    相关资源
    最近更新 更多