Вопрос

I am unable to store a form in a sqlite3 database using Flask-SQLAlchemy. My views.py is throwing the error below when I attempt to store the form.

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()])

How can I store this form?

Это было полезно?

Решение

SQLAlchemy's methods only work with SQLAlchemy objects - your issue is that you are passing an instance of WTForms Form class (which SQLAlchemy doesn't know how to persist to your database). You can map from your WTForms class to your SQLAlchemy object by using Form.populate_obj once you change your Form declaration to match the types in your Model class (gender, age, and education are all marked as Integer in your Model class, but are String fields in your Form class).

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

    form.populate_obj(model)

    db.session.add(model)
    db.session.commit()
    return redirect(url_for('index'))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top