WTForms SelectMultipleFields动态默认值

时间:2014-07-31 17:45:15

标签: python flask wtforms

我正在使用带Flask的WTForms,(不是Flask-wtf)。 我正在使用SelectMultipleFields动态设置选项;

class MyForm(Form):
    country = SelectMultipleField("Country", option_widget=widgets.CheckboxInput(),
       widget=widgets.ListWidget(prefix_label=False))

正如我所说,选择是动态的,我查询数据库以获取新的国家,然后我设置选择,类似于;

form = MyForm(request.form, obj=user) # obj = user's sqlalchemy object
form.country.choices = [(c.title(), c.title()) for c in get_distinct_countries()]

get_distinct_countries 查询数据库并返回国家/地区列表[('country a', 'country a'), ('country b', 'country b', (...)]

所有这一切都很好,但现在我想设置默认值,这也是动态的,所以我尝试了这个;

form = PersonalForm(request.form, obj=user)
form.country.choices = [(c.title(), c.title()) for c in get_distinct_countries()] # to fix
form.country.default = [(i.title(), i.title()) for i in get_user_country(userid)]

这是我的 get_countries get_user_country 函数;

def get_user_country(id): # todo
    with session_scope() as session:
        countries = session.query(UserCountry).filter_by(user_id=id)
    return [c.country for c in countries.all()]

def get_distinct_countries(): # todo
    """Returns a list of all countries (without duplication)"""
    with session_scope() as session:
        countries = session.query(Country).distinct(Country.country).group_by(Country.country)
    return [i.country.capitalize() for i in countries.all()]

get_user_country 的输出类似[('country a, 'country a'), (...)] 没有工作,我没有得到任何追溯,但在检查表单字段时,没有设置为默认值。我怎样才能做到这一点?

注意,我传递了obj = user,因为这是一个用户将重新编辑其设置的表单,所以我希望数据存在,显然我看到的一切都正确,除了国家的数据。

感谢。

3 个答案:

答案 0 :(得分:0)

我发现WTForms在默认情况下非常烦人,因为它不像你期望的那样工作。您可以通过default参数设置全局默认值,但不能按会话设置。

对于简单字段,您可以在视图中设置值:

@app.route('/some_route')
def flask_route():

    form = YourFormHere(obj=obj)

    form.some_field.data = "default data here"

    render_template('template.tmpl', form=form)

我不记得我是否已经为SelectMultipleFields做了这个 - 我在代码库中进行了快速搜索,但没有出现任何问题。希望这适合你。

答案 1 :(得分:0)

您是否尝试将default值设置为元组just the index

form.country.default = [i.title() for i in get_user_country(userid)]

答案 2 :(得分:0)

我意识到这已经很晚了,但我在谷歌搜索同一个问题时发现了这个页面。正如其他用户所指出的,要动态设置突出显示的字段,必须设置form.field.data(而不是form.field.default)。所需的选择必须包含在列表中(即使它是一个选择)。仅使用"值"您为选择提供的(值,标签)元组的成员。在您的情况下,代码将是:

form.country.data = [i.title() for i in get_user_country(userid)]

这不会起作用:

form.country.data = [(i.title(), i.title()) for i in get_user_country(userid)]

如果您想要一个默认值,那么这不会起作用:

form.country.data = "some value"

但这会:

form.country.data = ["some value"]