这个 [example][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
属性。没有任何效果。我错过了一些明显的东西吗?有人可以帮忙吗?
最佳答案
您需要将您的 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)
关于python - SQLAlchemy/WTForms : set default selected value for QuerySelectField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21579373/