python - SQLAlchemy/WTForms : set default selected value for QuerySelectField

标签 python sqlalchemy flask selection wtforms

这个 [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/

相关文章:

python - 动态调用属性 setter

python - 自动创建相关模型

javascript - 选择 flask 中的文件

Python Flask 故意空响应

python - Flask 应用程序无法正确呈现 html 标签

python - 使用多处理时共享无锁的ctypes numpy数组

python - 使用 python 将 RGB 值转换为等效的 HSV 值

python - SQLAlchemy 提交对通过 __dict__ 修改的对象的更改

python - 在 SQLAlchemy 中动态构造过滤器

Python QuerySelectField 和 request.form 返回字典键,而不是字典值