SQLAlchemy / WTForms: sets the selected default value to QuerySelectField

This [example] [1] to create a form with WTForms and SQLAlchemy in Flask and add a QuerySelectField to the form. I do not use flask.ext.sqlalchemymy code:

ContentForm = model_form(Content, base_class=Form)
ContentForm.author = QuerySelectField('Author', get_label="name")
myform = ContentForm(request.form, content)
myform.author.query = query_get_all(Authors)

Now I want to set the default value for the QuerySelectField selection list .

Tried to skip defaultkwarg in QuerySelectField and set attributes selected. Nothing succeeded. Am I missing something? Can anyone help?

+3
source share
2 answers

You need to set the keyword argument defaultto the instance Authorsyou want by default:

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

:

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

:

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

All Articles