Authenticated Forms

Associating form data with a user

Posting a message

Only logged in users should be able to post,
and their username should be associated.

Ensure the form is formatted correctly

Add the form action and form method,
plus names for all form inputs.

Allow POST data for new message route

@website.route('/new-message', methods=['GET', 'POST'])
@usermanager.login_required
def new_message():
    return render_template('new-message.html')

Add both POST and GET method options
to the new message route.

Handle both GET and POST methods

def new_message():

    if request.method == 'GET':
        return render_template('new-message.html')

    elif request.method == 'POST':
        return redirect('/')

Modify the new_message function
to handle both request types.

Get form data

def new_message():

    if request.method == 'GET':
        return render_template('new-message.html')

    elif request.method == 'POST':

        content = request.form.get('message')

        return redirect('/')

Get the message content from the form.

Import datetime so we can get the current time

from datetime import datetime

Import the dattime module at
the top of your routes file.

Generate current time

def new_message():

    if request.method == 'GET':
        return render_template('new-message.html')

    elif request.method == 'POST':

        content = request.form.get('message')
        current_time = datetime.now()

        return redirect('/')

Generate the current time.

Get logged in user id

def new_message():

    if request.method == 'GET':
        return render_template('new-message.html')

    elif request.method == 'POST':

        content = request.form.get('message')
        current_time = datetime.now()
        user_id = usermanager.current_user.user_id

        return redirect('/')

Write query

elif request.method == 'POST':

    content = request.form.get('message')
    current_time = datetime.now()
    user_id = usermanager.current_user.user_id

    query_string = (
      'INSERT INTO messages( content, time_created, user_id ) '
      'VALUES (?,?,?)'
    )

    return redirect('/')

Submit query with parameters

query_string = (
  'INSERT INTO messages( content, time_created, user_id ) '
  'VALUES (?,?,?)'
)

query_result = datamanager.query_db(
    query_string, 
    [content, current_time, user_id], 
    one=True
)

return redirect('/')

Check result is valid

query_result = datamanager.query_db(
    query_string, 
    [content, current_time, user_id], 
    one=True
)

if query_result == None:
    print('error')
else:
    print('success')

return redirect('/')

Check in browser

Try posting a message and check
that it shows up on the home page.

Thumbs Up!

Authenticated Forms: Complete!

Take me to the next chapter!

Loading...