Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask WTForms: how do I get a form value back into Python?

What I'm trying to do is get user input on 5 different fields, then have what the user entered available to use in the rest of my program in python. The code I have so far, looks like this:

class ArtistsForm(Form):
    artist1 = StringField('Artist 1', validators=[DataRequired()])
    artist2 = StringField('Artist 2', validators=[DataRequired()])
    artist3 = StringField('Artist 3', validators=[DataRequired()])
    artist4 = StringField('Artist 4', validators=[DataRequired()])
    artist5 = StringField('Artist 5', validators=[DataRequired()])


@app.route('/', methods=('GET', 'POST'))
def home():
    form = ArtistsForm(csrf_enabled=False)
    if form.validate_on_submit():
        return redirect('/results')
    return render_template('home.html', form=form)

@app.route('/results', methods=('GET', 'POST'))
def results():
    artist1 = request.form['artist1']
    artist2 = request.form['artist2']
    artist3 = request.form['artist3']
    artist4 = request.form['artist4']
    artist5 = request.form['artist5']

    return render_template('results.html')

Any ideas? (i know csrf_enabled=False is bad, I'm just doing it to test for now.) I want the values for a function below this, to do some computations (no web aspect).

EDIT: I updated my code above. I was able to get the values in. Now I just need to pass them to a function below.

like image 870
David Schuler Avatar asked Feb 10 '16 20:02

David Schuler


1 Answers

You need to populate some sort of data structure like a variable ,list, or a dictionary and then pass that to a python function. The return/result of the python function would then need to be passed as a context parameter to be rendered in your result template.

Example:

@app.route('/', methods=('GET', 'POST'))
def home():
    form = ArtistsForm(request.POST, csrf_enabled=False)
    if form.validate_on_submit():
        art1 = form.artist1.data
        art2 = form.artist2.data
        result = computate_uncertainty(art1, art2)
        return render_template('results.html', result=result)
    return render_template('home.html', form=form)
like image 105
m1yag1 Avatar answered Nov 15 '22 06:11

m1yag1