SQLAlchemy / WTForms:为QuerySelectField设置默认选定值

时间:2014-02-05 13:58:06

标签: python sqlalchemy flask selection wtforms

这个[示例] [1]在Flask中使用WTForms和SQLAlchemy设置表单,并在表单中添加QuerySelectField。我没有使用flask.ext.sqlalchemy,我的代码:

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)

现在我想设置QuerySelectField选择列表的默认值

尝试在QuerySelectField中传递default kwarg并设置selected属性。没有任何效果。我错过了一些明显的东西吗有人可以帮忙吗?

2 个答案:

答案 0 :(得分:4)

您需要将default关键字参数设置为您希望成为默认值的Authors实例:

# Hypothetically, let's 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)

答案 1 :(得分:0)

尝试一下:

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