Web Forms

Capturing user input

Prepare the sign in form

We need the form on the sign-in
page to be set up correctly.

Set the form action to sign-in

<form action="sign-in">

The form “action” is the URL or route
where the form data should be submitted.

Set the form method to post

<form action="sign-in" method="post">

Setting the method to “post” allows us to
easily access the data from within Python.

Name all form inputs

<form action="sign-in" method="post">

  <label>Username</label>
  <input name="username" type="text">

  <label>Password</label>
  <input name="password" type="password">

  <input type="submit" value="Sign in">

</form>

Form inputs must have a name attribute
for their data to be posted to the server.

Modify the sign in route

Our sign-in route now needs to process sign ins
as well as display the sign in form to users.

Import Flask’s request package

from flask import request

At the top of routes.py, import the
request package to allow us to process forms.

Define which methods are enabled for the route

@website.route('/sign-in', methods=['GET', 'POST'])
def sign_in():
    return render_template('sign-in.html')

The GET method is for viewing the web page,
and the POST method is for processing form data.

Do different things based on the method used

@website.route('/sign-in', methods=['GET', 'POST'])
def sign_in():

    if request.method == 'GET':
        return render_template('sign-in.html')

    if request.method == 'POST':
        return 'log in the user'

For a GET request we want to display the form,
but for POST we want to log in the user.

Check that both GET and POST are supported

Browse to the sign in page and ensue that
you get a different page when clicking sign in.

Get the posted username and password

if request.method == 'POST':

    username = request.form.get('username')
    password = request.form.get('password')

We can get the values entered in the form
by using the names we specified in the HTML.

Check the form fields in the shell

if request.method == 'POST':

    username = request.form.get('username')
    password = request.form.get('password')

    print('username:', username)
    print('password:', password)

Sign in with a username and password,
then check that they printed in the shell.

Thumbs Up!

Web Forms: Complete!

Take me to the next chapter!

Loading...