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

问题描述 投票:3回答:2

这个[例子] [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属性。没有任何效果。我错过了一些明显的东西吗有人可以帮忙吗?

python sqlalchemy flask selection wtforms
2个回答
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)

0
投票

试试这个:

ContentForm.author = QuerySelectField(
    'Author', 
    get_label="name", 
    default=lambda: Authors.get(current_user.id).one()
)
© www.soinside.com 2019 - 2024. All rights reserved.