我无法使用Flask-SQLAlchemy将表单存储在 sqlite3 数据库中。当我尝试存储表单时,我的views.py
会抛出以下错误。
UnmappedInstanceError: Class 'app.forms.Survey1' is not mapped
@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)
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)
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()])
如何存储此表单?
答案 0 :(得分:3)
SQLAlchemy的方法仅适用于SQLAlchemy对象 - 您的问题是您传递的是WTForms Form
类的实例(SQLAlchemy不知道如何持久保存到您的数据库)。一旦更改Form
声明以匹配Model
类中的类型({{{}},就可以使用Form.populate_obj
从WTForms类映射到您的SQLAlchemy对象1}},gender
和age
都在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'))