[英]Pass a variable to a Flask WTForm
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
我不知道如何将变量从 View 传递到 Form 类
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())
This is from the QuerySelectField documentation:这是来自QuerySelectField文档:
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.
如果未设置该属性,则将调用传递给字段构造函数的 query_factory 可调用以获取查询。
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():
# ...
See my other answer here: https://stackoverflow.com/a/17638018/880326 .在此处查看我的其他答案: https : //stackoverflow.com/a/17638018/880326 。
So it looks like:所以它看起来像:
form = transactionsForm(request.form, loan_id='default')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.