Related Tutorial

4: Passing Form Variables to Other Routes in Flask

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:

  1. Change the route from /about to /your-url and rename the function to your_url.
  2. Modify the function to render a template called your_url.html that we will create shortly.

Creating the Template

				
					<!-- your_url.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Your URL</title>
</head>
<body>
    <h1>Your URL</h1>
    <h2>Code: {{ code }}</h2>
</body>
</html>
				
			

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!