【问题标题】:Flask forms. How to make variable from views visible in forms.py烧瓶形式。如何在 forms.py 中使视图中的变量可见
【发布时间】:2015-03-05 17:42:43
【问题描述】:

我正在使用 Flask 和 WTForms。 我在烧瓶中有一个视图:

@app.route('/test/<bar>')
def foo(bar):
    form = SomeForm():
        if form.validate_on_submit():
            query = User(somedata = form.somedata.data,
                         another_data = form.anotherdata.data)
            db.session.add(query)
            db.session.commit()
            flash('ok')
            return redirect(url_for('main.index'))
    return render_template('test.html', form=form, bar=bar)

还有一个表格:

#imports here
    class SomeForm(Form):
        ch1 = SomeTable.query.filter_by(age='1').all()
        choice1 = SelectField('Select data', choices=[(e.name, e.name) for e in ch1])  

我需要从我的视图中获取变量“bar”并使其在我的表单中可见,以便在我的选择字段中使用 2 个条件(年龄和 bar)进行查询。

【问题讨论】:

    标签: python flask sqlalchemy flask-wtforms


    【解决方案1】:

    __init__ 中执行此操作,而不是在定义表单类时。

    class SomeForm(Form):
        def __init__(self, bar, *args, **kwargs):
            ch1 = SomeTable.query.filter_by(bar=bar)
            self.choice1.kwargs['choices'] = tuple((e.name, e.name) for e in ch1)
            super(SomeForm, self).__init__(*args, **kwargs)
    

    然后在视图中:

    form = SomeForm(bar)
    

    【讨论】:

      猜你喜欢
      • 2016-05-09
      • 2021-05-03
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多