0
0
Flaskframework~30 mins

Form field types in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Form field types
📖 Scenario: You are building a simple web form for a small business website using Flask. The form will collect user information including their name, email, age, and a message.
🎯 Goal: Create a Flask web form using different form field types to collect user data. The form should include text input, email input, number input, and a text area. This will help you understand how to use various form fields in Flask.
📋 What You'll Learn
Create a Flask app with a route for the form
Use Flask-WTF to create a form class with different field types
Include fields: StringField for name, EmailField for email, IntegerField for age, TextAreaField for message
Render the form in an HTML template with proper labels
💡 Why This Matters
🌍 Real World
Forms are essential for collecting user input on websites, such as contact forms, registration, and surveys.
💼 Career
Knowing how to create and handle forms in Flask is a key skill for backend web developers working with Python.
Progress0 / 4 steps
1
Set up Flask app and import FlaskForm
Create a Flask app by importing Flask and FlaskForm from flask_wtf. Initialize the app with app = Flask(__name__) and set app.config['SECRET_KEY'] = 'secret'.
Flask
Need a hint?

Remember to import Flask and FlaskForm, then create the app and set a secret key for forms.

2
Create a form class with different field types
Create a class called UserForm that inherits from FlaskForm. Add these fields: name as StringField, email as EmailField, age as IntegerField, and message as TextAreaField. Import these field types from wtforms. Add SubmitField named submit.
Flask
Need a hint?

Define the form class with the exact field names and types as instructed.

3
Create a route to display the form
Create a Flask route for '/' using @app.route('/'). Define a function index() that creates an instance of UserForm called form. Render a template called 'form.html' passing form=form.
Flask
Need a hint?

Use the @app.route decorator and create the index function that returns the form template.

4
Create the HTML template to render the form
Create a file named form.html. Use Jinja2 syntax to render the form fields inside a <form> tag with method post. Include labels and inputs for form.name, form.email, form.age, form.message, and the form.submit button. Use {{ form.csrf_token }} inside the form for security.
Flask
Need a hint?

Use Jinja2 syntax to render each form field with its label inside a form tag with method post.