← Back to Django Course | Chapter 10: Authentication & Authorization | Lesson 9 of 12

Password Hashing in Django

Django never writes your real password down — it scrambles it into a secret code that can be checked but never read back.

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.

bash
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.

bash
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.

bash
python manage.py shell

>>> user.check_password('EvenSaferPass2')
True
>>> user.check_password('WrongGuess')
False

⚠️ Run this command in your terminal.

Common Mistakes
  1. Storing plain-text passwords in a CharField instead of letting Django's User model hash them automatically.
  2. Comparing user.password directly to a submitted password string instead of using check_password() or authenticate().
  3. Rolling a custom hashing function instead of trusting Django's built-in, well-tested PASSWORD_HASHERS.
Chapter Summary
  • 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.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.