Password Hashing in Django
Why Hashing Matters
If a database were ever leaked, hashed passwords are useless to an attacker without enormous computing effort, unlike plain text passwords which are instantly readable.
Example: Why Hashing Matters
create_user() runs the password through Django's hasher automatically — the stored value is never the raw text.
python manage.py shell
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user(username='bob', password='SecurePass1')
>>> print(user.password)
pbkdf2_sha256$600000$...
⚠️ Run this command in your terminal.
Changing a Password Safely
set_password() re-hashes a new password and must be followed by save() to persist the change.
Note: Always call save() after set_password() — it only updates the in-memory object otherwise.
Example: Changing a Password Safely
set_password() hashes the new password in memory; save() writes the hashed value to the database.
python manage.py shell
>>> user.set_password('EvenSaferPass2')
>>> user.save()
⚠️ Run this command in your terminal.
Verifying a Password
check_password() safely compares a plain-text attempt against the stored hash, returning True or False.
Example: Verifying a Password
check_password() re-hashes the guess and compares hashes, so the real password is never exposed in the process.
python manage.py shell
>>> user.check_password('EvenSaferPass2')
True
>>> user.check_password('WrongGuess')
False
⚠️ Run this command in your terminal.
- Storing plain-text passwords in a CharField instead of letting Django's User model hash them automatically.
- Comparing user.password directly to a submitted password string instead of using check_password() or authenticate().
- Rolling a custom hashing function instead of trusting Django's built-in, well-tested PASSWORD_HASHERS.
- Django hashes passwords automatically using algorithms listed in PASSWORD_HASHERS (PBKDF2 by default).
- create_user() and set_password() hash the password; direct assignment to .password does not.
- check_password() verifies a plain password against the stored hash without ever decrypting it.
- Passwords can never be un-hashed back into their original text — only verified.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Introduction to Django's Auth System
- The User Model Overview
- Setting Up a Login View
- Logout Functionality
- User Registration Form
- The login_required Decorator
- The permission_required Decorator
- Django Groups and Permissions
- Password Hashing in Django
- Session Authentication Basics
- Introduction to Custom User Models
- Sending Emails with Django