python - flask WTForms : how do I get a form value back into Python?

标签 python flask wtforms

我想做的是在5个不同的字段上获取用户输入,然后让用户输入的内容可在python程序的其余部分中使用。到目前为止,我的代码如下所示:

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是不好的,我现在只是要进行测试。)我希望此函数下面的值进行一些计算(无网络方面)。

编辑:我更新了上面的代码。我能够获得这些值。现在,我只需要将它们传递给下面的函数。

最佳答案

您需要填充某种数据结构,例如变量,列表或字典,然后将其传递给python函数。然后需要将python函数的返回/结果作为上下文参数传递,以呈现在您的结果模板中。

例子:

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

关于python - flask WTForms : how do I get a form value back into Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325287/

相关文章:

python - Flask JWT 在每个请求上扩展 token 的有效性

python - python表单验证库的推荐

python - WTForms 从表单中以 unicode 格式导入数据

python - 从 DataFrame 中删除一列中仅包含一个唯一值的组

python - 中断 Python 单元测试时关闭资源

docker - DisabledBackend : Erratic Behavior with Celery, Redis & Flask

javascript - pdfkit 不加载 css 和 JavaScript

python - 错误 : IndexError: string index out of range. 试图颠倒列表的顺序

python - 如何获取单引号内的字符串但忽略 "' s "and " 't "?

python - Pylint - Pylint 无法导入 flask.ext.wtf?