🔐 Django Authentication: Your Website’s Bouncer
The Big Picture: What is Authentication?
Imagine you have a secret treehouse. Not everyone can climb up—only your best friends who know the secret password. That’s exactly what authentication does for websites!
graph TD A["🧒 Visitor Arrives"] --> B{Know the Password?} B -->|Yes! ✅| C["🎉 Welcome Inside!"] B -->|No ❌| D["🚪 Stay Outside"]
Authentication = Checking WHO you are
When you log into a website, it’s like showing your special membership card. The website checks: “Is this really you? Do you belong here?”
🧑 The User Model: Your Digital ID Card
Django gives every user a digital ID card called the User Model. Think of it like a library card that stores:
| Field | What It Means | Example |
|---|---|---|
username |
Your unique name | coolkid123 |
password |
Secret code (hidden!) | •••••••• |
email |
Your mail address | kid@mail.com |
first_name |
Your first name | Alex |
last_name |
Your family name | Smith |
is_active |
Can you enter? | True ✅ |
is_staff |
Special helper? | False |
is_superuser |
The big boss? | False |
📦 Where Does It Live?
from django.contrib.auth.models import User
This one line gives you access to all user magic!
🔍 Finding Users
# Find one user by username
user = User.objects.get(username='coolkid123')
# Find all active users
active_users = User.objects.filter(is_active=True)
# Check if a user exists
exists = User.objects.filter(email='kid@mail.com').exists()
🛠️ Creating Users in Code: Making New Members
Creating a user is like signing up a new friend for your club!
Method 1: The Safe Way (Recommended!)
from django.contrib.auth.models import User
# Create a regular user
new_user = User.objects.create_user(
username='newkid',
email='newkid@mail.com',
password='secretpass123'
)
Why use create_user()?
- It hashes (scrambles) the password so nobody can read it
- It’s like writing your password in a secret code!
Method 2: Creating a Superuser (The Boss!)
superuser = User.objects.create_superuser(
username='bigboss',
email='boss@mail.com',
password='verysecret123'
)
A superuser can do everything—like having a master key to every room!
⚠️ Never Do This!
# ❌ WRONG - Password stored in plain text!
user = User(username='oops', password='mypassword')
user.save()
# ✅ RIGHT - Password safely scrambled
user = User.objects.create_user('safe', password='mypassword')
🔑 Authentication Functions: The Doorkeeper’s Tools
Django has special helper functions to check visitors at the door.
1. authenticate() - Check the Password
from django.contrib.auth import authenticate
user = authenticate(
username='coolkid123',
password='secretpass123'
)
if user is not None:
print("Password correct! ✅")
else:
print("Wrong password! ❌")
Think of this like a bouncer checking your ID card against the guest list.
2. login() - Let Them In!
from django.contrib.auth import login
def my_login_view(request):
user = authenticate(
username='coolkid123',
password='secretpass123'
)
if user:
login(request, user)
# User is now logged in! 🎉
After login(), Django remembers this visitor everywhere they go on your site.
3. logout() - Say Goodbye
from django.contrib.auth import logout
def my_logout_view(request):
logout(request)
# User has left the building! 👋
graph TD A["User Visits"] --> B["authenticate"] B -->|Valid| C["login"] B -->|Invalid| D["Show Error"] C --> E["User Browses Site"] E --> F["logout"] F --> A
🛡️ Login Required Decorator: The VIP Gate
Some pages are only for logged-in users. The @login_required decorator is like a VIP rope!
Basic Usage
from django.contrib.auth.decorators import login_required
@login_required
def my_secret_page(request):
return render(request, 'secret.html')
What happens?
- ✅ Logged in? → See the secret page
- ❌ Not logged in? → Sent to login page
Custom Redirect
@login_required(login_url='/please-login/')
def vip_area(request):
return render(request, 'vip.html')
For Class-Based Views
from django.contrib.auth.mixins import LoginRequiredMixin
class SecretView(LoginRequiredMixin, View):
login_url = '/login/'
def get(self, request):
return render(request, 'secret.html')
🖥️ Authentication Views: Ready-Made Pages
Django gives you free login pages! No need to build from scratch.
Setting Up Built-in Views
In your urls.py:
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/',
auth_views.LoginView.as_view(),
name='login'),
path('logout/',
auth_views.LogoutView.as_view(),
name='logout'),
]
The Login Template
Create registration/login.html:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log In</button>
</form>
All Built-in Views
| View | What It Does |
|---|---|
LoginView |
Shows login form |
LogoutView |
Logs user out |
PasswordChangeView |
Change password |
PasswordResetView |
“Forgot password?” |
Settings to Remember
# settings.py
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/dashboard/'
LOGOUT_REDIRECT_URL = '/'
🔒 Password Management Views: Keep Secrets Safe
Changing Passwords (When Logged In)
# urls.py
path('password-change/',
auth_views.PasswordChangeView.as_view(),
name='password_change'),
path('password-change/done/',
auth_views.PasswordChangeDoneView.as_view(),
name='password_change_done'),
Resetting Forgotten Passwords
This needs 4 views (like 4 steps):
# Step 1: Enter your email
path('password-reset/',
auth_views.PasswordResetView.as_view(),
name='password_reset'),
# Step 2: "Check your email!"
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done'),
# Step 3: Click email link, enter new password
path('password-reset/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
# Step 4: "Success!"
path('password-reset/complete/',
auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete'),
graph TD A["😢 Forgot Password"] --> B["Enter Email"] B --> C["📧 Email Sent"] C --> D["Click Link"] D --> E["Enter New Password"] E --> F["🎉 Password Changed!"]
Email Settings Required
# settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your@email.com'
EMAIL_HOST_PASSWORD = 'your-password'
🎯 Quick Reference: The Complete Flow
graph TD A["🆕 New User"] --> B["create_user"] B --> C["User in Database"] D["🚪 Visitor"] --> E["LoginView"] E --> F["authenticate"] F -->|Valid| G["login"] F -->|Invalid| E G --> H["🎉 Logged In!"] H --> I{Protected Page?} I -->|Yes| J["@login_required"] J --> K["Show Content"] H --> L["LogoutView"] L --> M["logout"] M --> D H --> N["😢 Forgot Password?"] N --> O["Password Reset Flow"] O --> H
🌟 Remember This!
| When You Want To… | Use This… |
|---|---|
| Store user info | User model |
| Make a new user | create_user() |
| Check password | authenticate() |
| Log someone in | login() |
| Log someone out | logout() |
| Protect a page | @login_required |
| Quick login page | LoginView |
| Reset password | PasswordResetView |
You’ve learned the bouncer’s complete toolkit! 🎉
Now you can:
- Create users safely
- Let the right people in
- Keep strangers out
- Help forgetful friends reset their passwords
Go build something amazing! 🚀
