User registration, logins and WTForms - tstorrnetnz/teaching2025 GitHub Wiki

Introduction

The ability to control who is able to do or see certain things on your application (e.g. make posts) will be useful. This can be done by creating user accounts in Python Flask.

We will need to:

  1. Create a registration page with the right fields (name, email etc)
  2. Ensure that the correct details are completed (validated)
  3. Encrypt the password
  4. Store all the details in a Person Class in the database
  5. Redirect the user to a login page once they have registered
  6. When a login takes place, check the account exists
  7. If the account exists, check that the entered password matches the encrypted password in the database
  8. If all is correct, log the user in and set the status of the "session" to logged in
  9. Tag the pages that a logged in user can access, so that they can benefit from being logged in.

Fortunately Python Flask can handle this relatively easily (in combination with WTForms)

Tutorial

Screenshot from 2024-06-06 11-04-15

No single tutorial seems to cover exactly what we need, and no more.

The code and repl here:Github branch of WTForms user accounts and Repl WTFormsUserAccountDemo are my attempts at combining this youtube tutorial: Python Flask Authentication Tutorial - Learn Flask Login with our previous work on "pizzas/people and things". The code from the youtube tutorial can It works quite well!

You may also need to ensure the modules below are in your Python setup by importing them using pip:

Screenshot from 2025-05-30 09-58-19

Here are my notes that I made as I was making the application. I suggest that you watch the video with my example alongside and see how I modified it to work.

Some additional thoughts or improvements include:

  1. To show or hide parts of a page depending on if a user is logged in or not, it looks like you can use a current_user.is_authenticated() call see How to show/hide navbar item based on custom decorator admin role (Stackoverflow)
  2. Creating different user roles within your application is certainly possible - see Flask - role-based access control.
  3. A more simple alternative for us though may be to not have all the pages on the menu (i.e. hide ones for not logged in users) and have a separate menu on the user dashboard page.
  4. Password resets are probably beyond what we require for Level 3 - it is possible - only the very enthusiastic should look at Flask-Security-Too