Welcome back to CodeYourCraft! Today, we're diving into creating form classes in Flask. This lesson is perfect for beginners and intermediates, so let's get started! šÆ
Form classes in Flask are a way to create forms with a consistent structure, making your code cleaner and easier to manage. They help validate user input, reducing errors and making your application more robust. š”
Let's create a simple form class for a user registration.
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo, ValidationError
from models import User
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
email = User.query.filter_by(email=email.data).first()
if email is not None:
raise ValidationError('Please use a different email address.')š Note: Import the necessary modules and our User model from the models.py.
In the above code, we've created a form class called RegistrationForm that includes fields for username, email, password, and confirmation password. We've also added a validation method for each field:
validate_username: Checks if the username already exists in the database.validate_email: Checks if the email already exists in the database.Now let's use our RegistrationForm in a route.
from flask import render_template, flash, redirect, url_for
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
# Save the user to the database
user = User(username=form.username.data, email=form.email.data, password=form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you have registered!', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)š Note: We've imported the necessary Flask modules, and we're checking if the form is valid using the validate_on_submit() method. If the form is valid, we save the user to the database and redirect the user to the login page.
What does the `validate_on_submit()` method do in a Flask form class?
And that's it! You now know how to create form classes in Flask. This powerful technique will help you build cleaner, more robust applications. Happy coding! š