Back to Python
2026-01-136 min read

Login Form in Navbar

Learn Login Form in Navbar step by step with clear examples and exercises.

Why This Matters

A login form in a navbar is crucial for securing user accounts and providing personalized experiences on websites. It allows users to sign in, access their account information, and perform actions specific to their account, such as making purchases or managing settings. In this lesson, we'll learn how to create a functional login form within a navbar using Python and Flask, a popular web framework.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of the following:

  1. Python programming language
  2. HTML and CSS for structuring web pages
  3. JavaScript for client-side interactivity (optional but recommended)
  4. Flask web framework for building web applications in Python

Core Concept

In this section, we'll walk through the process of creating a login form within a navbar using Flask and HTML templates. We'll also cover server-side validation to ensure secure user authentication.

Setting up the project

First, make sure you have Flask installed on your system:

pip install flask

Next, create a new directory for your project and navigate into it:

mkdir login_form_navbar
cd login_form_navbar

Create a new file called app.py to contain our Flask application code. Also, create a folder named templates that will store our HTML templates.

Creating the HTML template for the navbar

Inside the templates folder, create a new file called base.html. This file will serve as the base template for all our pages:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Website{% endblock %}</title>
<!-- Add any necessary CSS and JavaScript files here -->
</head>
<body>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/login">Login</a></li>
{% if user %}
<li><a href="/logout">Logout</a></li>
{% endif %}
</ul>
</nav>
<!-- Add the content for each page here -->
{% block content %}{% endblock %}
</body>
</html>

In this template, we've created a simple navbar with links to the homepage and login page. If the user is authenticated (i.e., logged in), we also display a logout link.

Defining the application structure

Open app.py and set up the basic Flask app:

from flask import Flask, render_template, request, redirect, url_for, flash
app = Flask(__name__)

Set the secret key for session management

app.secret_key = 'your_secret_key'

Creating the login route and view

Next, we'll create a new route for the login page:

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':

Handle form submission here

pass

return render_template('login.html')


Create a new file called `login.html` inside the `templates` folder:

{% extends 'base.html' %}

{% block content %}

Login

Username:

Password:

Login

{% endblock %}


In this template, we've extended the base template and added a login form. When the user submits the form, the request will be sent to our `login()` function in `app.py`.

Implementing server-side validation and authentication

To keep our example simple, let's assume we have a list of predefined users with their passwords:

USERS = [
{'username': 'user1', 'password': 'pass1'},
{'username': 'user2', 'password': 'pass2'},
]

Inside the login() function, we can check if the submitted username and password match any of our predefined users:

if request.method == 'POST':
for user in USERS:
if request.form['username'] == user['username'] and request.form['password'] == user['password']:

Set the session variable to indicate the user is authenticated

app.session['user'] = user['username']

return redirect(url_for('home'))

flash('Invalid username or password')


If the login credentials are valid, we set a session variable to store the user's username and redirect them to the homepage. If the credentials are invalid, we display an error message.

Creating the home page

Finally, let's create a simple home page that checks if the user is authenticated and displays a personalized greeting:

@app.route('/')
def home():
if 'user' in app.session:
return render_template('home.html', user=app.session['user'])
return render_template('login.html')

Create a new file called home.html inside the templates folder:

{% extends 'base.html' %}

{% block content %}
<h1>Welcome, {{ user }}!</h1>
<!-- Add more content for the home page here -->
{% endblock %}

In this template, we've extended the base template and added a personalized greeting using the user variable passed from our home() function.

Running the application

To run your Flask app, save all files and run the following command in the terminal:

flask run

Now you can visit http://localhost:5000 in your web browser to see your login form in the navbar.

Worked Example

In this section, we'll walk through a complete example of creating a login form with server-side validation and authentication using Flask and HTML templates. You can find the full code for this example in the example folder of the login\_form\_navbar repository on GitHub.

Common Mistakes

  1. Forgetting to check if the request method is 'POST': Always check if the request method is 'POST' before attempting to access form data, as GET requests do not contain form data.
  2. Ignoring user input validation: Always validate user input on the server-side to prevent potential security issues such as SQL injection and cross-site scripting (XSS).
  3. Not using secure password hashing: Never store plaintext passwords. Use a secure password hashing algorithm like bcrypt or Argon2 to protect your users' passwords.
  4. Forgetting to log out users: Always provide a logout functionality to ensure that users are properly logged out when they choose to do so.
  5. Not using HTTPS: HTTPS encrypts the communication between the client and server, protecting sensitive data such as login credentials from being intercepted by malicious parties.

Practice Questions

  1. Modify the example provided in the example folder to use a secure password hashing algorithm like bcrypt.
  2. Implement a forgot password feature that sends a reset link to the user's email address.
  3. Add support for remembering users' login credentials using cookies.
  4. Implement a CAPTCHA to prevent automated bot attacks on your login form.
  5. Create a registration page where new users can create an account and set their own passwords.

FAQ

  1. Why is it important to validate user input on the server-side?

Validating user input on the server-side ensures that potentially harmful data, such as SQL injection attacks or cross-site scripting (XSS), cannot be injected into your application.

  1. What is a CAPTCHA and why should I use one?

A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a system used to differentiate between human users and automated bots. By implementing a CAPTCHA on your login form, you can help prevent brute-force attacks and other forms of automated abuse.

  1. Why should I use HTTPS for my web application?

HTTPS encrypts the communication between the client and server, protecting sensitive data such as login credentials from being intercepted by malicious parties. Using HTTPS is essential for any web application that handles user data.

  1. What are some best practices for password hashing?

Some best practices for password hashing include using a secure algorithm like bcrypt or Argon2, salting the password before hashing it, and storing only the hashed password (not the plaintext password).

  1. Why should I implement a logout functionality?

Implementing a logout functionality ensures that users are properly logged out when they choose to do so, protecting their account from unauthorized access. It is an essential feature for any web application that requires user authentication.

Login Form in Navbar | Python | XQA Learn