dizzy
dizzy

Reputation: 1277

SelectField WTforms not valid choice and sa_instance_state

I'm encountering a number of errors when implementing a WTForms SelectField in an application built with Flask/SQLalchemy.

Here's the relevant code:

Views.py:

form = ReviewForm()
    if form.validate_on_submit():
        review = Review(rating=form.rating.data, body=form.body.data, pub_date=datetime.utcnow(), author=g.user, item=thing)
        db.session.add(review)
        db.session.commit()

Models.py

RATING_CHOICES = (
        (1, '1'),
        (2, 2),
        (3, 3),
        (4, 4),
        (5, 5),
    )

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    pub_date = db.Column(db.DateTime)
    body = db.Column(db.Text)
    rating = db.Column(db.Integer)

Forms.py

class ReviewForm(Form):
    rating = SelectField('rating', choices=Review.RATING_CHOICES, validators=[Required()])
    body = TextAreaField('body', validators=[Required()])
    tags = StringField('tags', validators=[Required()])

So right now, with code as it is...I'm getting a "Not a valid choice" issue. I'm assuming it's interpreting my rating as a string or tuple or something and as a result, it isn't feeding properly to rating=db.column(db.Integer).

However, upon adding coerce=int to the selectfield arguments, I start encountering:

AttributeError: 'AnonymousUserMixin' object has no attribute '_sa_instance_state'

File "", line 194, in blank
review = Review(rating=form.rating.data, body=form.body.data, pub_date=datetime.utcnow(), author=g.user, item=thing)
File "<string>", line 4, in __init__

I'm clearly missing something here or sending something wrong...I'm just not savvy enough to dig into what the form is returning and figure it out.

Upvotes: 1

Views: 1219

Answers (1)

aviator
aviator

Reputation: 523

First of all you can always print from.data to see what data is being sent back for rating.

Now about you second error _sa_instance_state. Looks like it is being caused by your g.user. If this user is already present in the database sqlalchemy will just set the foreign key. If it is a new/anonymous user object, it will try to save user along with your Review.

Is your user of type AnonymousUserMixin ? If yes, are you missing db.Model in user's inheritance ?

Upvotes: 2

Related Questions