在 Flask 应用程序配置的 WTForms SelectField 中设置默认值?

Set default in WTForms SelectField from Flask app config?

我无法根据 Flask 应用程序中的配置值在 WTForms SelectField 中设置默认值。

我有一个 forms.py 文件,其中部分包括:

class MySearchForm(FlaskForm):
    title = StringField('Title')
    page_size = SelectField('Entries/page', choices=[(10, "10"), (25, "25"), (50, "50"), (100, "100")], default=25)
    # other stuff

尽管它似乎是正确的位置,但我无法通过将应用程序配置传递给此文件来使默认变量成为变量,因为我收到 "Working outside of application context" 错误。所以我想我必须在运行时在我的 Flask 视图中使用动态默认值来完成它。

我已经查看了其他一些关于此的 Whosebug 问题——主要的问题似乎是 How do you set a default value for a WTForms SelectField?——但我无法使它们中的任何一个起作用。

我的 routes.py 搜索视图大致是这样的:

form = MySearchForm(request.args)
if request.args: # if not, I display the search form
    if form.title.data:
        # construct relevant part of database query
    page_size = int(form.page_size.data)
    # other stuff: construct and execute DB query; render the view_results page

如果在 if request.args 语句之前,我按照建议尝试 form.page_size.default = current_app.config['PAGE_SIZE'] 然后 form.process(),这会清除搜索表单中的任何其他内容,因此 title不会通过的。如果我尝试 form.page_size.data = current_app.config['PAGE_SIZE'],它不会将配置值设置为表单中的默认值,只是在结果中。

我也尝试了 问题中讨论的技术,将我的 form 调用更改为 form = MySearchForm(request.args, page_size=current_app.config['PAGE_SIZE'])。这也不能正常工作:在初始调用时,表单没有选择任何内容(在这种特定情况下,因此显示值“10”);配置的值已正确用于搜索本身,但 page_size 的形式值仍为“10”。此外,实际上在表单中选择一个值没有任何效果;无论用户在表单中选择什么,都会使用配置的值。 (同样,手动更改 URL 中的 page_size 具有相同的行为。)

我该怎么做?

您需要检查您要设置的变量类型的一致性。

为此,在您的 SelectField 中使用参数 coerce

如果变量 app.config['PAGE_SIZE'] 是一个 int,您需要像这样声明您的表单字段:

page_size = SelectField('Entries/page',
    choices=[(10, "10"), (25, "25"), (50, "50"), (100, "100")],
    default=25,
    coerce=int)