bartezr
bartezr

Reputation: 789

Flask forms. How to make variable from views visible in forms.py

I'm using Flask and WTForms. I have a view in flask:

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

and a form:

#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])  

I'm need to get variable 'bar' from my view and make it visible in my form to make query with 2 conditions(age and bar) in my select field in form.

Upvotes: 0

Views: 263

Answers (1)

davidism
davidism

Reputation: 127280

Do this in __init__, not when defining the form class.

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)

Then in the view:

form = SomeForm(bar)

Upvotes: 1

Related Questions