KS
Killer-Skills

django-security — django-security ai agent django-security ai agent, django csrf protection setup, django sql injection prevention, configure django production.py settings, django authentication best practices, django secure deployment guide, django-security vs manual configuration, how to use django-security skill, django-security mcp install, django authorization roles implementation

Verified
v1.0.0
GitHub

About this Skill

Essential for Python Security Agents specializing in Django application hardening and vulnerability prevention. django-security is an AI agent skill that delivers expert guidance on Django security best practices. It helps developers implement authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and configure production security settings.

Features

Provides guidance on Django authentication and authorization setup
Assists in implementing user permissions and roles
Offers configuration advice for production security settings (e.g., settings/production.py)
Helps review Django applications for security vulnerabilities
Supports secure deployment configurations for production environments

# Core Topics

affaan-m affaan-m
[62.0k]
[7678]
Updated: 3/6/2026

Quality Score

Top 5%
89
Excellent
Based on code quality & docs
Installation
SYS Universal Install (Auto-Detect)
Cursor IDE Windsurf IDE VS Code IDE
> npx killer-skills add affaan-m/everything-claude-code/django-security

Agent Capability Analysis

The django-security MCP Server by affaan-m is an open-source Categories.official integration for Claude and other AI agents, enabling seamless task automation and capability expansion. Optimized for django-security ai agent, django csrf protection setup, django sql injection prevention.

Ideal Agent Persona

Essential for Python Security Agents specializing in Django application hardening and vulnerability prevention.

Core Value

Enables comprehensive Django security implementation including CSRF protection, SQL injection prevention, XSS mitigation, and secure authentication/authorization systems. Provides production-ready security configurations and deployment hardening guidelines.

Capabilities Granted for django-security MCP Server

Implementing Django authentication systems
Configuring production security settings
Preventing SQL injection vulnerabilities
Setting up CSRF protection mechanisms
Hardening Django deployment configurations

! Prerequisites & Limits

  • Django framework specific only
  • Requires Python environment
  • Needs access to Django project settings
Project
SKILL.md
15.2 KB
.cursorrules
1.2 KB
package.json
240 B
Ready
UTF-8
SKILL.md
Readonly

Django Security Best Practices

Comprehensive security guidelines for Django applications to protect against common vulnerabilities.

When to Activate

  • Setting up Django authentication and authorization
  • Implementing user permissions and roles
  • Configuring production security settings
  • Reviewing Django application for security issues
  • Deploying Django applications to production

Core Security Settings

Production Settings Configuration

python
1# settings/production.py 2import os 3 4DEBUG = False # CRITICAL: Never use True in production 5 6ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',') 7 8# Security headers 9SECURE_SSL_REDIRECT = True 10SESSION_COOKIE_SECURE = True 11CSRF_COOKIE_SECURE = True 12SECURE_HSTS_SECONDS = 31536000 # 1 year 13SECURE_HSTS_INCLUDE_SUBDOMAINS = True 14SECURE_HSTS_PRELOAD = True 15SECURE_CONTENT_TYPE_NOSNIFF = True 16SECURE_BROWSER_XSS_FILTER = True 17X_FRAME_OPTIONS = 'DENY' 18 19# HTTPS and Cookies 20SESSION_COOKIE_HTTPONLY = True 21CSRF_COOKIE_HTTPONLY = True 22SESSION_COOKIE_SAMESITE = 'Lax' 23CSRF_COOKIE_SAMESITE = 'Lax' 24 25# Secret key (must be set via environment variable) 26SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') 27if not SECRET_KEY: 28 raise ImproperlyConfigured('DJANGO_SECRET_KEY environment variable is required') 29 30# Password validation 31AUTH_PASSWORD_VALIDATORS = [ 32 { 33 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 34 }, 35 { 36 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 37 'OPTIONS': { 38 'min_length': 12, 39 } 40 }, 41 { 42 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 43 }, 44 { 45 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 46 }, 47]

Authentication

Custom User Model

python
1# apps/users/models.py 2from django.contrib.auth.models import AbstractUser 3from django.db import models 4 5class User(AbstractUser): 6 """Custom user model for better security.""" 7 8 email = models.EmailField(unique=True) 9 phone = models.CharField(max_length=20, blank=True) 10 11 USERNAME_FIELD = 'email' # Use email as username 12 REQUIRED_FIELDS = ['username'] 13 14 class Meta: 15 db_table = 'users' 16 verbose_name = 'User' 17 verbose_name_plural = 'Users' 18 19 def __str__(self): 20 return self.email 21 22# settings/base.py 23AUTH_USER_MODEL = 'users.User'

Password Hashing

python
1# Django uses PBKDF2 by default. For stronger security: 2PASSWORD_HASHERS = [ 3 'django.contrib.auth.hashers.Argon2PasswordHasher', 4 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 5 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 6 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 7]

Session Management

python
1# Session configuration 2SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # Or 'db' 3SESSION_CACHE_ALIAS = 'default' 4SESSION_COOKIE_AGE = 3600 * 24 * 7 # 1 week 5SESSION_SAVE_EVERY_REQUEST = False 6SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Better UX, but less secure

Authorization

Permissions

python
1# models.py 2from django.db import models 3from django.contrib.auth.models import Permission 4 5class Post(models.Model): 6 title = models.CharField(max_length=200) 7 content = models.TextField() 8 author = models.ForeignKey(User, on_delete=models.CASCADE) 9 10 class Meta: 11 permissions = [ 12 ('can_publish', 'Can publish posts'), 13 ('can_edit_others', 'Can edit posts of others'), 14 ] 15 16 def user_can_edit(self, user): 17 """Check if user can edit this post.""" 18 return self.author == user or user.has_perm('app.can_edit_others') 19 20# views.py 21from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin 22from django.views.generic import UpdateView 23 24class PostUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): 25 model = Post 26 permission_required = 'app.can_edit_others' 27 raise_exception = True # Return 403 instead of redirect 28 29 def get_queryset(self): 30 """Only allow users to edit their own posts.""" 31 return Post.objects.filter(author=self.request.user)

Custom Permissions

python
1# permissions.py 2from rest_framework import permissions 3 4class IsOwnerOrReadOnly(permissions.BasePermission): 5 """Allow only owners to edit objects.""" 6 7 def has_object_permission(self, request, view, obj): 8 # Read permissions allowed for any request 9 if request.method in permissions.SAFE_METHODS: 10 return True 11 12 # Write permissions only for owner 13 return obj.author == request.user 14 15class IsAdminOrReadOnly(permissions.BasePermission): 16 """Allow admins to do anything, others read-only.""" 17 18 def has_permission(self, request, view): 19 if request.method in permissions.SAFE_METHODS: 20 return True 21 return request.user and request.user.is_staff 22 23class IsVerifiedUser(permissions.BasePermission): 24 """Allow only verified users.""" 25 26 def has_permission(self, request, view): 27 return request.user and request.user.is_authenticated and request.user.is_verified

Role-Based Access Control (RBAC)

python
1# models.py 2from django.contrib.auth.models import AbstractUser, Group 3 4class User(AbstractUser): 5 ROLE_CHOICES = [ 6 ('admin', 'Administrator'), 7 ('moderator', 'Moderator'), 8 ('user', 'Regular User'), 9 ] 10 role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='user') 11 12 def is_admin(self): 13 return self.role == 'admin' or self.is_superuser 14 15 def is_moderator(self): 16 return self.role in ['admin', 'moderator'] 17 18# Mixins 19class AdminRequiredMixin: 20 """Mixin to require admin role.""" 21 22 def dispatch(self, request, *args, **kwargs): 23 if not request.user.is_authenticated or not request.user.is_admin(): 24 from django.core.exceptions import PermissionDenied 25 raise PermissionDenied 26 return super().dispatch(request, *args, **kwargs)

SQL Injection Prevention

Django ORM Protection

python
1# GOOD: Django ORM automatically escapes parameters 2def get_user(username): 3 return User.objects.get(username=username) # Safe 4 5# GOOD: Using parameters with raw() 6def search_users(query): 7 return User.objects.raw('SELECT * FROM users WHERE username = %s', [query]) 8 9# BAD: Never directly interpolate user input 10def get_user_bad(username): 11 return User.objects.raw(f'SELECT * FROM users WHERE username = {username}') # VULNERABLE! 12 13# GOOD: Using filter with proper escaping 14def get_users_by_email(email): 15 return User.objects.filter(email__iexact=email) # Safe 16 17# GOOD: Using Q objects for complex queries 18from django.db.models import Q 19def search_users_complex(query): 20 return User.objects.filter( 21 Q(username__icontains=query) | 22 Q(email__icontains=query) 23 ) # Safe

Extra Security with raw()

python
1# If you must use raw SQL, always use parameters 2User.objects.raw( 3 'SELECT * FROM users WHERE email = %s AND status = %s', 4 [user_input_email, status] 5)

XSS Prevention

Template Escaping

django
1{# Django auto-escapes variables by default - SAFE #} 2{{ user_input }} {# Escaped HTML #} 3 4{# Explicitly mark safe only for trusted content #} 5{{ trusted_html|safe }} {# Not escaped #} 6 7{# Use template filters for safe HTML #} 8{{ user_input|escape }} {# Same as default #} 9{{ user_input|striptags }} {# Remove all HTML tags #} 10 11{# JavaScript escaping #} 12<script> 13 var username = {{ username|escapejs }}; 14</script>

Safe String Handling

python
1from django.utils.safestring import mark_safe 2from django.utils.html import escape 3 4# BAD: Never mark user input as safe without escaping 5def render_bad(user_input): 6 return mark_safe(user_input) # VULNERABLE! 7 8# GOOD: Escape first, then mark safe 9def render_good(user_input): 10 return mark_safe(escape(user_input)) 11 12# GOOD: Use format_html for HTML with variables 13from django.utils.html import format_html 14 15def greet_user(username): 16 return format_html('<span class="user">{}</span>', escape(username))

HTTP Headers

python
1# settings.py 2SECURE_CONTENT_TYPE_NOSNIFF = True # Prevent MIME sniffing 3SECURE_BROWSER_XSS_FILTER = True # Enable XSS filter 4X_FRAME_OPTIONS = 'DENY' # Prevent clickjacking 5 6# Custom middleware 7from django.conf import settings 8 9class SecurityHeaderMiddleware: 10 def __init__(self, get_response): 11 self.get_response = get_response 12 13 def __call__(self, request): 14 response = self.get_response(request) 15 response['X-Content-Type-Options'] = 'nosniff' 16 response['X-Frame-Options'] = 'DENY' 17 response['X-XSS-Protection'] = '1; mode=block' 18 response['Content-Security-Policy'] = "default-src 'self'" 19 return response

CSRF Protection

Default CSRF Protection

python
1# settings.py - CSRF is enabled by default 2CSRF_COOKIE_SECURE = True # Only send over HTTPS 3CSRF_COOKIE_HTTPONLY = True # Prevent JavaScript access 4CSRF_COOKIE_SAMESITE = 'Lax' # Prevent CSRF in some cases 5CSRF_TRUSTED_ORIGINS = ['https://example.com'] # Trusted domains 6 7# Template usage 8<form method="post"> 9 {% csrf_token %} 10 {{ form.as_p }} 11 <button type="submit">Submit</button> 12</form> 13 14# AJAX requests 15function getCookie(name) { 16 let cookieValue = null; 17 if (document.cookie && document.cookie !== '') { 18 const cookies = document.cookie.split(';'); 19 for (let i = 0; i < cookies.length; i++) { 20 const cookie = cookies[i].trim(); 21 if (cookie.substring(0, name.length + 1) === (name + '=')) { 22 cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 23 break; 24 } 25 } 26 } 27 return cookieValue; 28} 29 30fetch('/api/endpoint/', { 31 method: 'POST', 32 headers: { 33 'X-CSRFToken': getCookie('csrftoken'), 34 'Content-Type': 'application/json', 35 }, 36 body: JSON.stringify(data) 37});

Exempting Views (Use Carefully)

python
1from django.views.decorators.csrf import csrf_exempt 2 3@csrf_exempt # Only use when absolutely necessary! 4def webhook_view(request): 5 # Webhook from external service 6 pass

File Upload Security

File Validation

python
1import os 2from django.core.exceptions import ValidationError 3 4def validate_file_extension(value): 5 """Validate file extension.""" 6 ext = os.path.splitext(value.name)[1] 7 valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.pdf'] 8 if not ext.lower() in valid_extensions: 9 raise ValidationError('Unsupported file extension.') 10 11def validate_file_size(value): 12 """Validate file size (max 5MB).""" 13 filesize = value.size 14 if filesize > 5 * 1024 * 1024: 15 raise ValidationError('File too large. Max size is 5MB.') 16 17# models.py 18class Document(models.Model): 19 file = models.FileField( 20 upload_to='documents/', 21 validators=[validate_file_extension, validate_file_size] 22 )

Secure File Storage

python
1# settings.py 2MEDIA_ROOT = '/var/www/media/' 3MEDIA_URL = '/media/' 4 5# Use a separate domain for media in production 6MEDIA_DOMAIN = 'https://media.example.com' 7 8# Don't serve user uploads directly 9# Use whitenoise or a CDN for static files 10# Use a separate server or S3 for media files

API Security

Rate Limiting

python
1# settings.py 2REST_FRAMEWORK = { 3 'DEFAULT_THROTTLE_CLASSES': [ 4 'rest_framework.throttling.AnonRateThrottle', 5 'rest_framework.throttling.UserRateThrottle' 6 ], 7 'DEFAULT_THROTTLE_RATES': { 8 'anon': '100/day', 9 'user': '1000/day', 10 'upload': '10/hour', 11 } 12} 13 14# Custom throttle 15from rest_framework.throttling import UserRateThrottle 16 17class BurstRateThrottle(UserRateThrottle): 18 scope = 'burst' 19 rate = '60/min' 20 21class SustainedRateThrottle(UserRateThrottle): 22 scope = 'sustained' 23 rate = '1000/day'

Authentication for APIs

python
1# settings.py 2REST_FRAMEWORK = { 3 'DEFAULT_AUTHENTICATION_CLASSES': [ 4 'rest_framework.authentication.TokenAuthentication', 5 'rest_framework.authentication.SessionAuthentication', 6 'rest_framework_simplejwt.authentication.JWTAuthentication', 7 ], 8 'DEFAULT_PERMISSION_CLASSES': [ 9 'rest_framework.permissions.IsAuthenticated', 10 ], 11} 12 13# views.py 14from rest_framework.decorators import api_view, permission_classes 15from rest_framework.permissions import IsAuthenticated 16 17@api_view(['GET', 'POST']) 18@permission_classes([IsAuthenticated]) 19def protected_view(request): 20 return Response({'message': 'You are authenticated'})

Security Headers

Content Security Policy

python
1# settings.py 2CSP_DEFAULT_SRC = "'self'" 3CSP_SCRIPT_SRC = "'self' https://cdn.example.com" 4CSP_STYLE_SRC = "'self' 'unsafe-inline'" 5CSP_IMG_SRC = "'self' data: https:" 6CSP_CONNECT_SRC = "'self' https://api.example.com" 7 8# Middleware 9class CSPMiddleware: 10 def __init__(self, get_response): 11 self.get_response = get_response 12 13 def __call__(self, request): 14 response = self.get_response(request) 15 response['Content-Security-Policy'] = ( 16 f"default-src {CSP_DEFAULT_SRC}; " 17 f"script-src {CSP_SCRIPT_SRC}; " 18 f"style-src {CSP_STYLE_SRC}; " 19 f"img-src {CSP_IMG_SRC}; " 20 f"connect-src {CSP_CONNECT_SRC}" 21 ) 22 return response

Environment Variables

Managing Secrets

python
1# Use python-decouple or django-environ 2import environ 3 4env = environ.Env( 5 # set casting, default value 6 DEBUG=(bool, False) 7) 8 9# reading .env file 10environ.Env.read_env() 11 12SECRET_KEY = env('DJANGO_SECRET_KEY') 13DATABASE_URL = env('DATABASE_URL') 14ALLOWED_HOSTS = env.list('ALLOWED_HOSTS') 15 16# .env file (never commit this) 17DEBUG=False 18SECRET_KEY=your-secret-key-here 19DATABASE_URL=postgresql://user:password@localhost:5432/dbname 20ALLOWED_HOSTS=example.com,www.example.com

Logging Security Events

python
1# settings.py 2LOGGING = { 3 'version': 1, 4 'disable_existing_loggers': False, 5 'handlers': { 6 'file': { 7 'level': 'WARNING', 8 'class': 'logging.FileHandler', 9 'filename': '/var/log/django/security.log', 10 }, 11 'console': { 12 'level': 'INFO', 13 'class': 'logging.StreamHandler', 14 }, 15 }, 16 'loggers': { 17 'django.security': { 18 'handlers': ['file', 'console'], 19 'level': 'WARNING', 20 'propagate': True, 21 }, 22 'django.request': { 23 'handlers': ['file'], 24 'level': 'ERROR', 25 'propagate': False, 26 }, 27 }, 28}

Quick Security Checklist

CheckDescription
DEBUG = FalseNever run with DEBUG in production
HTTPS onlyForce SSL, secure cookies
Strong secretsUse environment variables for SECRET_KEY
Password validationEnable all password validators
CSRF protectionEnabled by default, don't disable
XSS preventionDjango auto-escapes, don't use &#124;safe with user input
SQL injectionUse ORM, never concatenate strings in queries
File uploadsValidate file type and size
Rate limitingThrottle API endpoints
Security headersCSP, X-Frame-Options, HSTS
LoggingLog security events
UpdatesKeep Django and dependencies updated

Remember: Security is a process, not a product. Regularly review and update your security practices.

Related Skills

Looking for an alternative to django-security or building a Categories.official AI Agent? Explore these related open-source MCP Servers.

View All

flags

Logo of facebook
facebook

flags is a feature flag management system that enables developers to check flag states, compare channels, and debug feature behavior differences across release channels.

243.6k
0
Design

extract-errors

Logo of facebook
facebook

extract-errors is a skill that assists in extracting and managing error codes in React applications using yarn extract-errors command.

243.6k
0
Design

fix

Logo of facebook
facebook

fix is a technical skill that resolves lint errors, formatting issues, and ensures code quality in declarative, frontend, and UI projects

243.6k
0
Design

flow

Logo of facebook
facebook

Flow is a type checking system for JavaScript, used to validate React code and ensure consistency across applications

243.6k
0
Design