Redirect to other view after submitting form

Question:

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)
Asked By: tommy

||

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.

Answered By: davidism

Though I am not specifically answering your current question I found myself with a similar problem with getting the page to redirect after the submission button had been clicked. So I hope this solution could potentially work for others that find themselevs in a similar predicament.

This example uses Flask forms for handling forms and submissions.

from flast_wtf import FlaskForm

@app.route("/", methods=["GET", "POST"])
def home():
    stock_form = StockForm()
    tick = stock_form.text_field.data
    if tick != None:
        return redirect(f'/{tick}', code=302)
    return render_template("home.html", template_form=stock_form, ticker=tick)

The if statement checks that the submission after being clicked has a value, then redirects to your chosen link. This code is a copy and paste from a badly programmed stock price lookup.

Answered By: TAG
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.