Back to Python
2026-03-107 min read

Toggle Password Visibility (Python Programming)

Learn Toggle Password Visibility (Python Programming) step by step with clear examples and exercises.

Why This Matters

In this comprehensive tutorial, we will delve into creating a secure password field that hides text input during entry, an essential feature in modern web applications to maintain user privacy and data security. By learning how to implement this feature using Python with Flask, you'll not only enhance your programming skills but also contribute to building more secure web applications.

Prerequisites

To fully grasp the concepts presented in this tutorial, it is recommended that you have a basic understanding of:

  1. Python programming language
  2. Web development fundamentals (HTML, CSS)
  3. Flask, a lightweight web framework for Python
  4. Python's built-in libraries like os, sys, and jinja2
  5. Basic JavaScript concepts to manipulate the DOM
  6. Familiarity with web security best practices
  7. Understanding of HTML5 and its features, such as the type="password" attribute for hiding password inputs
  8. Knowledge of server-side programming concepts like hashing, salting, and storing passwords securely
  9. Experience with Flask's routing system and template rendering
  10. Familiarity with web security best practices such as CSRF protection

Core Concept

To create a password field that hides user input, we will employ HTML for defining the form structure, use JavaScript to toggle visibility upon clicking an icon, and implement server-side logic using Flask. This tutorial will also cover securely storing passwords on the server-side using hashing and salting.

First, let's set up our project structure:

password_visibility/
├── app.py
├── static/
│ └── css/
│ └── style.css
│ └── js/
│ └── toggle_password.js
├── templates/
│ └── base.html
│ └── index.html

Now, let's create the necessary files:

app.py

This is our main Flask application file.

from flask import Flask, render_template, request, redirect, url_for, flash, session
import bcrypt
from jinja2 import Environment, FileSystemLoader

app = Flask(__name__)
env = Environment(loader=FileSystemLoader('templates'))

app.secret_key = "YOUR_SECRET_KEY" # Set a secret key for secure sessions

@app.route('/')
def index():
return render_template('index.html', title='Toggle Password Visibility')

@app.route('/login', methods=['POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
user = User.query.filter_by(email=email).first()

Check if the user exists and the provided password is correct

if user and bcrypt.check_password_hash(user.password, password):

session['user_id'] = user.id

return redirect(url_for('home'))

else:

flash("Invalid email or password")

return render_template('index.html', title='Login')

@app.route('/register', methods=['GET', 'POST'])

def register():

if request.method == 'POST':

email = request.form['email']

password = bcrypt.generate_password_hash(request.form['password']).decode('utf-8') # Hash the password using bcrypt

user = User(email=email, password=password)

db.session.add(user)

db.session.commit()

flash("Account created successfully!")

return redirect(url_for('index'))

return render_template('register.html', title='Register')

if __name__ == '__main__':

app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///db.sqlite3" # Set up the database connection

db.init_app(app)

app.run(debug=True)


### base.html

This template file will serve as the base structure for our web pages, including common elements like the header and footer.

{% block title %}{% endblock %}

{% block css %}

{% endblock %}

{% block content %}

{% endblock %}

{% block js %}

{% endblock %}


### index.html

This HTML template file will include the password field and JavaScript to toggle visibility.

{% extends 'base.html' %}

{% block content %}

Password Toggle Example

Email:

Password:

Login

Register

{% endblock %}

document.addEventListener('DOMContentLoaded', function() {

const passwordInput = document.getElementById('password');

const showPasswordButton = document.createElement('button');

showPasswordButton.innerHTML = 'Show';

showPasswordButton.onclick = function() {

if (passwordInput.type === 'password') {

passwordInput.type = 'text';

showPasswordButton.innerHTML = 'Hide';

} else {

passwordInput.type = 'password';

showPasswordButton.innerHTML = 'Show';

}

};

passwordInput.insertAdjacentElement('afterend', showPasswordButton);

});


### style.css

This CSS file will position the "Show" and "Hide" buttons next to the password input field.

#password {

width: 200px;

}

#password + button {

margin-left: 5px;

}


Now, run your Flask application and open a web browser to `http://localhost:5000`. You should see the password field with the "Show" button next to it. Try clicking the button to toggle visibility!

Common Mistakes

  1. Forgetting to include the JavaScript file in the HTML template (index.html)
  2. Not defining the toggle_password.js script correctly
  3. Failing to position the "Show" and "Hide" buttons next to the password input field (CSS)
  4. Not using Flask's built-in functions like render_template, request, redirect, url_for, and flash in app.py
  5. Overlooking security best practices such as hashing and salting passwords before storing them on the server-side
  6. Failing to validate user input for common issues like empty email or password fields, weak passwords, or incorrect login attempts
  7. Not properly handling errors and exceptions during development and production
  8. Implementing CSRF protection using Flask-WTF or Flask-CSP (see the Flask documentation for more information)
  9. Using outdated hashing algorithms or insecure storage methods for passwords
  10. Failing to secure the database connection by not setting up a secret key or using an unencrypted connection

Practice Questions

  1. Modify the example to store the entered password securely on the server-side instead of just displaying it. Consider using a hashing algorithm like SHA-256 and salting the password before storing it in the database.
  2. Implement a similar feature for hiding and showing a credit card number input field.
  3. Add validation to ensure that the entered email is valid, the password meets certain requirements (e.g., minimum length, at least one uppercase letter, etc.), and the user has not exceeded the maximum number of failed login attempts.
  4. Secure your application by implementing CSRF protection using Flask-WTF or Flask-CSP
  5. Implement a password recovery system where users can recover their passwords via email.
  6. Add a feature to remember the user's email for future logins.
  7. Implement a rate limiter to prevent brute force attacks on the login page.
  8. Implement a secure connection using HTTPS for all requests.
  9. Store the salt used for hashing passwords securely and separately from the hashed password itself.
  10. Implement a feature to log user activity, such as failed login attempts or successful logins, for auditing purposes.

Worked Example

In this section, we will walk through a worked example of implementing the password visibility toggle using Python with Flask.

Step 1: Set up the project structure

Create a new directory called password_visibility and navigate to it in your terminal.

mkdir password_visibility
cd password_visibility

Step 2: Initialize a virtual environment

It's a good practice to create a separate virtual environment for each project. This ensures that the dependencies for this specific project are isolated and won't interfere with other projects.

python3 -m venv env
source env/bin/activate # On Windows, use `env\Scripts\activate` instead

Step 3: Install Flask and other required packages

Now that the virtual environment is set up, we can install Flask and its dependencies.

pip install flask flask-sqlalchemy flask-bcrypt

Step 4: Create the main application file (app.py)

Create a new file called app.py in the project directory and paste the code provided earlier.

Step 5: Create the HTML templates

Next, create the necessary HTML files for our web pages.

mkdir static
mkdir templates
touch app.py static/css/style.css static/js/toggle_password.js templates/base.html templates/index.html

Step 6: Add the JavaScript code to toggle password visibility

Open static/js/toggle_password.js and paste the provided JavaScript code.

Step 7: Add the CSS code to position the "Show" and "Hide" buttons

Open static/css/style.css and paste the provided CSS code.

Step 8: Implement the server-side logic for hashing passwords

Update the app.py file with the following code to create a User model, define a database connection, and implement hashing and salting of passwords.

from flask import Flask, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)

if __name__ == '__main__':
app.run(debug=True)

Step 9: Create the database and tables

Run the following command to create the database and tables for our application.

python -c "from app import db; db.create_all()"

Step 10: Update the index.html file with the password field and JavaScript toggle button

Open templates/index.html and paste the provided HTML code for the password field and JavaScript toggle button.

Step 11: Run the application

Finally, run your Flask application by executing the following command in your terminal.

python app.py

Now, open a web browser to http://localhost:5000. You should see the password field with the "Show" button next to it. Try clicking the button to toggle visibility!

FAQ

  1. Why not use HTML5's type="password" attribute for hiding the password input? While this is a good approach for client-side masking, it doesn't prevent attackers from accessing the plaintext password data on the server-side. In our example, we are focusing on the server-side implementation using Flask and securely storing passwords.
  1. Why not use a library or package to handle password visibility toggling? Using a dedicated library can make your code more concise and easier to maintain, but it's beneficial to understand the underlying concepts and implement them yourself for better understanding of how things work under the hood.
Toggle Password Visibility (Python Programming) | Python | XQA Learn