0
0
Flaskframework~30 mins

Why form handling matters in Flask - See It in Action

Choose your learning style9 modes available
Why form handling matters
📖 Scenario: You are building a simple web page where users can submit their favorite color. This color will be saved and shown back to them. Handling forms correctly is important to get user input and respond properly.
🎯 Goal: Create a Flask app that shows a form to enter a favorite color, accepts the form submission, and then displays the chosen color on a new page.
📋 What You'll Learn
Create a Flask app with a route for the form page
Add a form in HTML with a text input named color and a submit button
Create a route to handle the form submission using POST method
Display the submitted color on a new page after submission
💡 Why This Matters
🌍 Real World
Form handling is essential for websites to get user input like login info, search queries, or preferences.
💼 Career
Understanding form handling is a key skill for web developers working with backend frameworks like Flask.
Progress0 / 4 steps
1
Set up Flask app and form route
Create a Flask app instance called app and add a route for '/' that returns an HTML form with a text input named color and a submit button. Use the POST method in the form tag.
Flask
Need a hint?

Remember to create the Flask app instance and define a route for '/' that returns the HTML form with method POST.

2
Check for form submission and get color
Inside the home function, add code to check if the request method is POST. If yes, get the submitted color from request.form using the key 'color' and save it in a variable called favorite_color.
Flask
Need a hint?

Use request.method == 'POST' to check if the form was submitted, then get the value with request.form['color'].

3
Show the submitted color after form submission
Modify the home function so that if favorite_color is set (not None), it returns a page showing the text Your favorite color is: {favorite_color} instead of the form.
Flask
Need a hint?

Use an f-string to insert favorite_color into the returned HTML string.

4
Run the Flask app
Add the code to run the Flask app only if the script is run directly. Use app.run(debug=True) inside the if __name__ == '__main__': block.
Flask
Need a hint?

Use the standard Python check if __name__ == '__main__': to run app.run(debug=True).