2015-07-21 86 views
6

我有一个调查表。提交表单后,我想处理保存数据,然后重定向到“成功”视图。我现在正在使用下面的代码,但它只停留在当前的URL上,而我想去/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) 

回答

5

您有一个正确的目标:在处理表单数据后重定向很好。而不是再次返回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') 

重定向将通过用户的浏览器进行处理,并在新的URL新的页面将被加载,而不是在相同的URL渲染不同的模板。

+0

你也可以使用[flash messages](http://flask.pocoo.org/docs/0.10/patterns/flashing/)。 – dirn