Skip to content Skip to sidebar Skip to footer

Sqlalchemy/wtforms: Set Default Selected Value For Queryselectfield

This [example][1] to set up a form with WTForms and SQLAlchemy in Flask and add a QuerySelectField to the form works. I am not using flask.ext.sqlalchemy, my code: ContentForm = mo

Solution 1:

You need to set your default keyword argument to the instance of Authors that you want to be the default:

# Hypothetically, let's say that the current user makes the most sense# This is just an example, for the sake of the thinguser = Authors.get(current_user.id)
ContentForm.author = QuerySelectField('Author', get_label='name', default=user)

Alternately, you can provide the instance to the field on instantiation:

# The author keyword will only be checked if# author is not in request.form or contentmyform = ContentForm(request.form, obj=content, author=user)

Solution 2:

Try this:

ContentForm.author = QuerySelectField(
    'Author', 
    get_label="name", 
    default=lambda: Authors.get(current_user.id).one()
)

Post a Comment for "Sqlalchemy/wtforms: Set Default Selected Value For Queryselectfield"