I. Skill Overview
This skill provides a systematic set of security best practices for Django applications, covering all security dimensions of Django services from production environment configuration to deployment and operations.
Applicable scenarios: Setting up Django authentication and authorization, configuring production security settings, reviewing Django application security issues, deploying Django applications to production.
Core principle: Security is a process, not a product—regularly review and update security practices.
II. Core Functions
1. Production Environment Security Configuration
| Configuration Item | Recommended Value | Description |
|---|---|---|
| DEBUG | False | Never enable in production |
| ALLOWED_HOSTS | Environment variable list | Restrict allowed hosts |
| SECURE_SSL_REDIRECT | True | Force HTTPS redirect |
| SECURE_HSTS_SECONDS | 31536000 | 1-year HSTS |
| SESSION_COOKIE_SECURE / CSRF_COOKIE_SECURE | True | Cookies transmitted only over HTTPS |
| X_FRAME_OPTIONS | 'DENY' | Prevent clickjacking |
| SECURE_CONTENT_TYPE_NOSNIFF | True | Prevent MIME type sniffing |
SECRET_KEY must be set via environment variables, never hardcoded or committed to version control.
2. Password Validation
Enable all Django built-in password validators, requiring a password length of no less than 12 characters:
-
UserAttributeSimilarityValidator– prevent passwords similar to user attributes -
MinimumLengthValidator– minimum length 12 characters -
CommonPasswordValidator– prevent use of common weak passwords -
NumericPasswordValidator– prevent purely numeric passwords
3. Authentication
Custom User Model: Use email as the username field for enhanced security:
class User(AbstractUser):
email = models.EmailField(unique=True)
USERNAME_FIELD = 'email' # Use email as login credential
Password Hashing: Prefer stronger hashing algorithms like Argon2:
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.Argon2PasswordHasher', # Most secure
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
]
Session Management: Configure cached session engine, cookie expiry, and SameSite attributes.
4. Authorization
Model-level permissions: Define custom permissions in Meta.permissions:
class Meta:
permissions = [
('can_publish', 'Can publish posts'),
('can_edit_others', 'Can edit posts of others'),
]
View-level permissions: Use LoginRequiredMixin and PermissionRequiredMixin to protect views.
Custom permissions: Create custom permission classes such as IsOwnerOrReadOnly, IsAdminOrReadOnly for DRF APIs.
Role-Based Access Control (RBAC): Define role fields (admin/moderator/user) in the user model and create corresponding Mixins.
5. SQL Injection Protection
Django ORM automatically escapes parameters by default, which is safe:
User.objects.get(username=username) # Safe
When using raw() to execute raw SQL, always use parameter binding and never concatenate strings:
# Safe
User.objects.raw('SELECT * FROM users WHERE username = %s', [query])
# ❌ Dangerous – SQL injection vulnerability
User.objects.raw(f'SELECT * FROM users WHERE username = {username}')
Using Q objects to build complex queries is also safe.
6. XSS Protection
Django templates auto-escape variables by default:
{{ user_input }} {# Auto-escapes HTML #}
Security practices:
-
Only use the
|safefilter when handling trusted HTML -
Use
|striptagsto remove all HTML tags -
Use
format_htmlto safely build HTML containing variables -
Never use
mark_safedirectly on user input
7. CSRF Protection
Django enables CSRF protection by default:
-
CSRF_COOKIE_SECURE = True– transmit only over HTTPS -
CSRF_COOKIE_HTTPONLY = True– prevent JavaScript access -
CSRF_COOKIE_SAMESITE = 'Lax'
Use {% csrf_token %} in templates; for AJAX requests, obtain the CSRF token from cookies and include it in the request header.
Use @csrf_exempt with caution: only exempt when absolutely necessary (e.g., external webhooks).
8. File Upload Security
File validation: Validate file extensions (whitelist) and file size (max 5MB):
valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.pdf']
if filesize > 5 * 1024 * 1024:
raise ValidationError('File too large.')
Secure storage:
-
Store media files outside the web root
-
In production, serve media files using a separate domain or CDN (e.g., S3)
9. API Security
Rate limiting: Differentiate throttling policies for anonymous and authenticated users:
DEFAULT_THROTTLE_RATES = {
'anon': '100/day',
'user': '1000/day',
'upload': '10/hour',
}
API authentication: Use TokenAuthentication or JWT:
DEFAULT_AUTHENTICATION_CLASSES = [
'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
]
Protect API views with @permission_classes([IsAuthenticated]).
10. Security Headers
Content Security Policy (CSP): Restrict sources for loading scripts, styles, images, etc.:
CSP_DEFAULT_SRC = "'self'"
CSP_SCRIPT_SRC = "'self' https://cdn.example.com"
Add security headers via custom middleware:
-
X-Content-Type-Options: nosniff -
X-Frame-Options: DENY -
X-XSS-Protection: 1; mode=block
11. Secret Management
Use python-decouple or django-environ to read sensitive configurations from a .env file:
SECRET_KEY = env('DJANGO_SECRET_KEY')
DATABASE_URL = env('DATABASE_URL')
ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')
The .env file must never be committed to version control.
12. Security Event Logging
Configure loggers to capture django.security and django.request events:
'loggers': {
'django.security': {
'handlers': ['file', 'console'],
'level': 'WARNING',
},
}
III. Quick Security Checklist
| Check Item | Description | |
|---|---|---|
| DEBUG = False | Never enable DEBUG in production | |
| HTTPS only | Enforce SSL, use secure cookies | |
| Strong secret key | Use environment variables for SECRET_KEY | |
| Password validation | Enable all password validators | |
| CSRF protection | Enabled by default, do not disable | |
| XSS protection | Django auto-escapes; do not use | safe on user input |
| SQL injection | Use ORM; never concatenate strings in queries | |
| File upload | Validate file type and size | |
| Rate limiting | Restrict API endpoint access frequency | |
| Security headers | CSP, X-Frame-Options, HSTS | |
| Logging | Log security events | |
| Updates | Keep Django and its dependencies up to date |
IV. Primary Use Cases
-
New project security baseline – establish a complete security protection system when initializing Django projects
-
Pre-deployment checklist – verify key configurations such as
DEBUG=False, HTTPS enforcement, externalized secrets, etc. -
Security audits and code reviews – check against the checklist for common vulnerabilities in authentication, authorization, CSRF, XSS, SQL injection, etc.
-
API security hardening – configure rate limiting, authentication mechanisms, and permission controls
-
Team security training – serve as a reference document for secure coding standards for Django development teams
V. Important Principles
-
DEBUG never on:
DEBUGmust beFalsein production -
Secrets not in repo:
SECRET_KEYinjected via environment variables, never committed to version control -
Deny by default: Use
LoginRequiredMixinand permission classes to protect sensitive views -
Parameterized queries: When using raw SQL, always use parameter binding; never concatenate strings
-
Auto-escaping first: Django templates escape by default; only use
|safewhen handling trusted content -
Keep CSRF enabled: Do not use
@csrf_exemptcarelessly -
File upload validation: Validate file type (whitelist) and size
-
Rate limiting required: All API endpoints should have rate limiting configured
-
Log sanitization: Ensure logs do not record passwords, tokens, or other sensitive information
-
Regular updates: Keep Django and all dependencies up to date
VI. Summary
Django Security is a comprehensive set of Django application security best practices, covering 12 core security areas: production environment configuration, authentication and authorization, SQL injection protection, XSS protection, CSRF protection, file upload security, API rate limiting, security headers, secret management, and security event logging. It provides clear code examples and a step-by-step quick security checklist, suitable for new project security baselines, pre-deployment checks, code audits, and team security training. This skill originates from the ECC project and emphasizes that "security is a process, not a product."