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

自闭症网瘾萝莉.ら 提交于 2019-12-05 02:25:49

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/35325287/flask-wtforms-how-do-i-get-a-form-value-back-into-python

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