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

cas*_*ual 6 python sqlalchemy selection flask 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)
Run Code Online (Sandbox Code Playgroud)

现在我想设置 QuerySelectField 的 selectlist 的默认值

尝试default在 QuerySelectField 中传递 kwarg 并设置selected属性。什么都没起作用。我错过了一些明显的东西吗?有人可以帮忙吗?

Sea*_*ira 5

您需要将关键字参数设置为您希望成为默认值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)
Run Code Online (Sandbox Code Playgroud)

或者,您可以在实例化时向字段提供实例:

# The author keyword will only be checked if
# author is not in request.form or content
myform = ContentForm(request.form, obj=content, author=user)
Run Code Online (Sandbox Code Playgroud)