Flask WTForms:如何将表单值重新带回Python? [英] Flask WTForms: how do I get a form value back into Python?
问题描述
我想做的是在5个不同的字段上获取用户输入,然后让用户输入的内容可在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')
有什么想法吗?(我知道csrf_enabled = False是不好的,我现在就来进行测试.)我希望在此函数下面的值进行一些计算(无网络方面).
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).
我更新了上面的代码.我能够获得这些值.现在,我只需要将它们传递给下面的函数即可.
I updated my code above. I was able to get the values in. Now I just need to pass them to a function below.
推荐答案
您需要填充某种数据结构,例如变量,列表或字典,然后将其传递给python函数.然后需要将python函数的返回/结果作为上下文参数传递,以呈现在结果模板中.
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.
示例:
@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)
这篇关于Flask WTForms:如何将表单值重新带回Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!