Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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', 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)
like image 648
tommy Avatar asked Jul 21 '15 14:07

tommy


1 Answers

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

@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', 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', result_id=result.id))

    # 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.

like image 182
davidism Avatar answered Nov 02 '22 23:11

davidism