2015-07-21 61 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