提交表单后重定向到其他视图

时间:2015-07-21 14:41:49

标签: python redirect flask

我有一份调查表。提交表单后,我想处理保存数据然后重定向到“成功”视图。我现在正在使用以下代码,但它只保留在当前网址上,而我想转到/success。我怎么能这样做?

@app.route('/surveytest', methods=['GET', 'POST'])
def surveytest():
    if request.method == 'GET':
        return render_template('test.html', title='Survey Test', year=datetime.now().year, message='This is the survey page.')
    elif request.method == 'POST':
        name = request.form['name']
        address = request.form['address']
        phone = request.form['phone']
        email = request.form['email']
        company = request.form['company']
        return render_template('success.html', name=name, address=address, phone = phone, email = email, company = company)

1 个答案:

答案 0 :(得分:10)

您有正确的目标:处理表单数据后重定向很好。而不是再次返回render_template,而是使用redirect

from flask import redirect, url_for, survey_id

@app.route('/success/<int:result_id>')
def success(result_id):
     # replace this with a query from whatever database you're using
     result = get_result_from_database(result_id)
     # access the result in the tempalte, for example {{ result.name }}
     return render_template('success.html', result=result)

@app.route('/survey')
def survey():
    if request.method == 'POST':
        # replace this with an insert into whatever database you're using
        result = store_result_in_database(request.args)
        return redirect(url_for('success', result_id=result.id))

    # don't need to test request.method == 'GET'
    return render_template('survey.html')

重定向将由用户的浏览器处理,并且将加载新网址的新页面,而不是在同一网址上呈现不同的模板。