Flask Tutorial: Passing Form Variables to Other Routes
In this Flask tutorial, we will explore how to pass form variables to other routes in a Flask application. We will focus on creating a new route called “your-url” to handle form submissions and display the submitted data back to the user.
Setting Up the Route
To begin, we need to create a new route in our Flask application to handle the form submission. Follow these steps:
- Change the route from
/about
to/your-url
and rename the function toyour_url
. - Modify the function to render a template called
your_url.html
that we will create shortly.
Creating the Template
Your URL
Your URL
Code: {{ code }}
In the template, we use Jinja to display the code
variable that we will pass from the form submission.
Accessing Form Data
To access the form data submitted by the user, we need to import request
at the top of our Python file:
from flask import Flask, render_template, request
Then, within the your_url
function, we can access the form data using request.args
:
@app.route('/your-url')
def your_url():
code = request.args.get('code')
return render_template('your_url.html', code=code)
Displaying the Form Data
By passing the code
variable to the template, we can display the submitted data back to the user. When the user submits the form, the code
parameter will be displayed on the your-url
page.
Conclusion
By following these steps, you can successfully pass form variables to other routes in your Flask application. This tutorial demonstrates how to handle form submissions, access the submitted data, and display it back to the user using Jinja templates.
Stay tuned for the next part of this tutorial, where we will discuss how to change the form submission into a post request for more secure data handling.
Happy coding with Flask!