Now that we’ve got a database setup, our dinner application is starting to take shape. We’re going to need to get some data from our friends in order to make their dinner party accounts.
We could get all kinds of juicy information from them like their favorite dish or favorite chef, but for now, we’ll just grab their email address, username, and password. To get this information we’ll need to provide the user with an interface that has input areas for the respective fields that need to be filled out. An HTML form is a perfect way to gather this data!
We will use WTForms to create forms that make it easy for us to grab the data we need.
class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) password2 = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Register')
- a class
RegistrationFormis defined and inherits from
password2are defined with the appropriate validators to ensure the same password is entered twice
And we will have a route that allows the users to create an account.
@app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() return render_template('register.html', form=form)
- if the form is validated upon submission, a
useris created with a
user‘s password is set and hashed using the
useris added to the database session and the session is committed
Lastly, we need to make sure to update our template file to make sure the form is displayed properly to our users.
A registration form for users of our dinner party application has been started as the class
RegistrationForm in app.py. Add a class attribute named
StringField with label “Email”. Include the
Email() validators as well.
Add two more class attributes to
RegistrationForm for recording password information as described below:
- an attribute named
password, assigned as a
PasswordFieldwith label “Password”. Include the
- an attribute named
password2, assigned as a
PasswordFieldwith label “Repeat Password”. Include the
In the registration route, define a new
user with a username and email pulled from the registration form named
Set the password of
user with its
Once completed, try using the registration form and visiting the index route to see the users currently registered for the dinner party!