将变量传递给Flask WTForm [英] Pass a variable to a Flask WTForm

查看:112
本文介绍了将变量传递给Flask WTForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用从路由传入的默认值来执行查询选择字段.我不知道如何将变量从View传递到Form类

I want to do a query select field with a default value that is passed in from the route. I can't figure out how to pass a variable from the View to the Form class

class transactionsForm(Form):

loan_id = QuerySelectField('trans_id', validators=[Required()], get_label='name',
                           query_factory=lambda: trans.query.filter_by(trans_id=[MY VARIABLE]).all())

推荐答案

这来自

可以在视图中设置字段的查询属性,以按实例为该字段分配查询.如果未设置该属性,则将调用传递给字段构造函数的query_factory可调用对象以获取查询.

The query property on the field can be set from within a view to assign a query per-instance to the field. If the property is not set, the query_factory callable passed to the field constructor will be called to obtain a query.

这意味着您通过查询定义表单:

What this means is that you define your form with the query:

class transactionsForm(Form):
    loan_id = QuerySelectField('trans_id', validators=[Required()], get_label='name')

然后在您的视图函数中,一旦拥有实例,便分配查询:

And then in your view function you assign the query once you have an instance:

def viewFunction(my_variable):
    form = transactionsForm()
    my_query = trans.query.filter_by(trans_id=my_variable)
    form.loan_id.query = my_query
    if form.validate_on_submit():
        # ...

这篇关于将变量传递给Flask WTForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆