django.contrib.auth là module auth built-in: model User, hash password (PBKDF2 mặc định), session-based login/logout, decorator @login_required, hệ thống permission (group, permission), template tag {% if user.is_authenticated %}, view sẵn cho login/logout/password reset.
from django.contrib.auth import authenticate, login, logout
def signin(request):
user = authenticate(request, username=email, password=password)
if user:
login(request, user)
return redirect('home')
return render(request, 'login.html', {'error': 'Invalid'})Session lưu trong DB (bảng django_session) hoặc Redis nếu set SESSION_ENGINE = 'django.contrib.sessions.backends.cache'. Cookie chỉ giữ session key, không giữ data thực.
Một thứ rất quan trọng cho dự án mới: User.username mặc định unique và dài 150 ký tự, không phù hợp với app dùng email làm username. Phải luôn tạo custom user (xem [[#9227]]) trước khi migrate lần đầu — đổi AUTH_USER_MODEL sau khi đã có data là rất đau.
django.contrib.auth is the built-in auth module: the User model, password hashing (PBKDF2 by default), session-based login/logout, the @login_required decorator, a permission system (group, permission), the {% if user.is_authenticated %} template tag, and ready-made views for login/logout/password reset.
from django.contrib.auth import authenticate, login, logout
def signin(request):
user = authenticate(request, username=email, password=password)
if user:
login(request, user)
return redirect('home')
return render(request, 'login.html', {'error': 'Invalid'})Sessions live in the DB (django_session table) or Redis with SESSION_ENGINE = 'django.contrib.sessions.backends.cache'. The cookie only holds the session key, not the data.
Pitfall: The default User.username is unique with length 150 — a bad fit for email-as-username apps. New projects should always create a custom user (see [[#9227]]) before the first migrate, because changing AUTH_USER_MODEL after data exists is painful.