Redirect to other view after submitting form


I have a survey form. After submitting the form, I’d like to handle saving the data then redirect to a "success" view. I’m using the following code right now, but it just stays on the current url, while I’d like to go to /success. How can I do this?

@app.route('/surveytest', methods=['GET', 'POST'])
def surveytest():
    if request.method == 'GET':
        return render_template('test.html', title='Survey Test',, 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)


You have the right goal: it’s good to redirect after handling form data. Rather than returning render_template again, use redirect instead.

from flask import redirect, url_for, survey_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 {{ }}
     return render_template('success.html', result=result)

@app.route('/survey', methods=["GET", "POST"])
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',

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

The redirect will be handled by the user’s browser, and the new page at the new url will be loaded, rather than rendering a different template at the same url.

Answered By – davidism

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published