Pass a variable to a Flask WTForm

我们两清 提交于 2019-12-06 14:00:05

问题


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())

回答1:


This is from the QuerySelectField documentation:

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():
        # ...



回答2:


See my another ansver: https://stackoverflow.com/a/17638018/880326.

So it look like:

form = transactionsForm(request.form, loan_id='default')


来源:https://stackoverflow.com/questions/17980432/pass-a-variable-to-a-flask-wtform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!