Redirecting to another view after submitting the form

I have a profile. After submitting the form, I would like to process the data storage and then redirect to the "sucess" view. I am using the following code right now, but it just stays at the current URL, while I would 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) 
+6
source share
1 answer

You have the right goal: it is useful to redirect after processing the form data. Instead of returning render_template , use redirect again.

 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') 

The redirect will be processed by the user's browser, and a new page at the new URL will be loaded, and will not display another template at the same URL.

+5
source

All Articles