[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DAY7HRE2TAJTW414PFPMZX":3,"skill-same:01M7DAY7HRE2TAJTW414PFPMZX":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M7DAY7HRE2TAJTW414PFPMZX","django-security",null,"Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations. Use when reviewing Django authentication, authorization, input handling, or deployment settings.","MoradDev\u002Fskills-unified","MoradDev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F72839584?v=4","01M7DASN3HYHFBYW4ZNMPTHQ63","01M7DASN4N6P4P9WMEFRE2V0TF",2,"MIT","https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fdjango-security\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: django-security\ndescription: Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations. Use when reviewing Django authentication, authorization, input handling, or deployment settings.\nmetadata:\n  origin: ECC\n---\n\n# Django Security Best Practices\n\nComprehensive security guidelines for Django applications to protect against common vulnerabilities.\n\n## When to Activate\n\n- Setting up Django authentication and authorization\n- Implementing user permissions and roles\n- Configuring production security settings\n- Reviewing Django application for security issues\n- Deploying Django applications to production\n\n## Core Security Settings\n\n### Production Settings Configuration\n\n```python\n# settings\u002Fproduction.py\nimport os\n\nDEBUG = False  # CRITICAL: Never use True in production\n\nALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')\n\n# Security headers\nSECURE_SSL_REDIRECT = True\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\nSECURE_HSTS_SECONDS = 31536000  # 1 year\nSECURE_HSTS_INCLUDE_SUBDOMAINS = True\nSECURE_HSTS_PRELOAD = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nX_FRAME_OPTIONS = 'DENY'\n\n# HTTPS and Cookies\nSESSION_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SAMESITE = 'Lax'\nCSRF_COOKIE_SAMESITE = 'Lax'\n\n# Secret key (must be set via environment variable)\nSECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')\nif not SECRET_KEY:\n    raise ImproperlyConfigured('DJANGO_SECRET_KEY environment variable is required')\n\n# Password validation\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n        'OPTIONS': {\n            'min_length': 12,\n        }\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n    },\n]\n```\n\n## Authentication\n\n### Custom User Model\n\n```python\n# apps\u002Fusers\u002Fmodels.py\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\nclass User(AbstractUser):\n    \"\"\"Custom user model for better security.\"\"\"\n\n    email = models.EmailField(unique=True)\n    phone = models.CharField(max_length=20, blank=True)\n\n    USERNAME_FIELD = 'email'  # Use email as username\n    REQUIRED_FIELDS = ['username']\n\n    class Meta:\n        db_table = 'users'\n        verbose_name = 'User'\n        verbose_name_plural = 'Users'\n\n    def __str__(self):\n        return self.email\n\n# settings\u002Fbase.py\nAUTH_USER_MODEL = 'users.User'\n```\n\n### Password Hashing\n\n```python\n# Django uses PBKDF2 by default. For stronger security:\nPASSWORD_HASHERS = [\n    'django.contrib.auth.hashers.Argon2PasswordHasher',\n    'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n]\n```\n\n### Session Management\n\n```python\n# Session configuration\nSESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # Or 'db'\nSESSION_CACHE_ALIAS = 'default'\nSESSION_COOKIE_AGE = 3600 * 24 * 7  # 1 week\nSESSION_SAVE_EVERY_REQUEST = False\nSESSION_EXPIRE_AT_BROWSER_CLOSE = False  # Better UX, but less secure\n```\n\n## Authorization\n\n### Permissions\n\n```python\n# models.py\nfrom django.db import models\nfrom django.contrib.auth.models import Permission\n\nclass Post(models.Model):\n    title = models.CharField(max_length=200)\n    content = models.TextField()\n    author = models.ForeignKey(User, on_delete=models.CASCADE)\n\n    class Meta:\n        permissions = [\n            ('can_publish', 'Can publish posts'),\n            ('can_edit_others', 'Can edit posts of others'),\n        ]\n\n    def user_can_edit(self, user):\n        \"\"\"Check if user can edit this post.\"\"\"\n        return self.author == user or user.has_perm('app.can_edit_others')\n\n# views.py\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.views.generic import UpdateView\n\nclass PostUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n    model = Post\n    permission_required = 'app.can_edit_others'\n    raise_exception = True  # Return 403 instead of redirect\n\n    def get_queryset(self):\n        \"\"\"Only allow users to edit their own posts.\"\"\"\n        return Post.objects.filter(author=self.request.user)\n```\n\n### Custom Permissions\n\n```python\n# permissions.py\nfrom rest_framework import permissions\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n    \"\"\"Allow only owners to edit objects.\"\"\"\n\n    def has_object_permission(self, request, view, obj):\n        # Read permissions allowed for any request\n        if request.method in permissions.SAFE_METHODS:\n            return True\n\n        # Write permissions only for owner\n        return obj.author == request.user\n\nclass IsAdminOrReadOnly(permissions.BasePermission):\n    \"\"\"Allow admins to do anything, others read-only.\"\"\"\n\n    def has_permission(self, request, view):\n        if request.method in permissions.SAFE_METHODS:\n            return True\n        return request.user and request.user.is_staff\n\nclass IsVerifiedUser(permissions.BasePermission):\n    \"\"\"Allow only verified users.\"\"\"\n\n    def has_permission(self, request, view):\n        return request.user and request.user.is_authenticated and request.user.is_verified\n```\n\n### Role-Based Access Control (RBAC)\n\n```python\n# models.py\nfrom django.contrib.auth.models import AbstractUser, Group\n\nclass User(AbstractUser):\n    ROLE_CHOICES = [\n        ('admin', 'Administrator'),\n        ('moderator', 'Moderator'),\n        ('user', 'Regular User'),\n    ]\n    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='user')\n\n    def is_admin(self):\n        return self.role == 'admin' or self.is_superuser\n\n    def is_moderator(self):\n        return self.role in ['admin', 'moderator']\n\n# Mixins\nclass AdminRequiredMixin:\n    \"\"\"Mixin to require admin role.\"\"\"\n\n    def dispatch(self, request, *args, **kwargs):\n        if not request.user.is_authenticated or not request.user.is_admin():\n            from django.core.exceptions import PermissionDenied\n            raise PermissionDenied\n        return super().dispatch(request, *args, **kwargs)\n```\n\n## SQL Injection Prevention\n\n### Django ORM Protection\n\n```python\n# GOOD: Django ORM automatically escapes parameters\ndef get_user(username):\n    return User.objects.get(username=username)  # Safe\n\n# GOOD: Using parameters with raw()\ndef search_users(query):\n    return User.objects.raw('SELECT * FROM users WHERE username = %s', [query])\n\n# BAD: Never directly interpolate user input\ndef get_user_bad(username):\n    return User.objects.raw(f'SELECT * FROM users WHERE username = {username}')  # VULNERABLE!\n\n# GOOD: Using filter with proper escaping\ndef get_users_by_email(email):\n    return User.objects.filter(email__iexact=email)  # Safe\n\n# GOOD: Using Q objects for complex queries\nfrom django.db.models import Q\ndef search_users_complex(query):\n    return User.objects.filter(\n        Q(username__icontains=query) |\n        Q(email__icontains=query)\n    )  # Safe\n```\n\n### Extra Security with raw()\n\n```python\n# If you must use raw SQL, always use parameters\nUser.objects.raw(\n    'SELECT * FROM users WHERE email = %s AND status = %s',\n    [user_input_email, status]\n)\n```\n\n## XSS Prevention\n\n### Template Escaping\n\n```django\n{# Django auto-escapes variables by default - SAFE #}\n{{ user_input }}  {# Escaped HTML #}\n\n{# Explicitly mark safe only for trusted content #}\n{{ trusted_html|safe }}  {# Not escaped #}\n\n{# Use template filters for safe HTML #}\n{{ user_input|escape }}  {# Same as default #}\n{{ user_input|striptags }}  {# Remove all HTML tags #}\n\n{# JavaScript escaping #}\n\u003Cscript>\n    var username = {{ username|escapejs }};\n\u003C\u002Fscript>\n```\n\n### Safe String Handling\n\n```python\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import escape\n\n# BAD: Never mark user input as safe without escaping\ndef render_bad(user_input):\n    return mark_safe(user_input)  # VULNERABLE!\n\n# GOOD: Escape first, then mark safe\ndef render_good(user_input):\n    return mark_safe(escape(user_input))\n\n# GOOD: Use format_html for HTML with variables\nfrom django.utils.html import format_html\n\ndef greet_user(username):\n    return format_html('\u003Cspan class=\"user\">{}\u003C\u002Fspan>', escape(username))\n```\n\n### HTTP Headers\n\n```python\n# settings.py\nSECURE_CONTENT_TYPE_NOSNIFF = True  # Prevent MIME sniffing\nX_FRAME_OPTIONS = 'DENY'  # Prevent clickjacking\n\n# Custom middleware\nfrom django.conf import settings\n\nclass SecurityHeaderMiddleware:\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        response = self.get_response(request)\n        response['X-Content-Type-Options'] = 'nosniff'\n        response['X-Frame-Options'] = 'DENY'\n        response['X-XSS-Protection'] = '1; mode=block'\n        response['Content-Security-Policy'] = \"default-src 'self'\"\n        return response\n```\n\n## CSRF Protection\n\n### Default CSRF Protection\n\n```python\n# settings.py - CSRF is enabled by default\nCSRF_COOKIE_SECURE = True  # Only send over HTTPS\nCSRF_COOKIE_HTTPONLY = False  # False so AJAX can read csrf token from document.cookie; SESSION_COOKIE_HTTPONLY remains True\nCSRF_COOKIE_SAMESITE = 'Lax'  # Prevent CSRF in some cases\nCSRF_TRUSTED_ORIGINS = ['https:\u002F\u002Fexample.com']  # Trusted domains\n\n# Template usage\n\u003Cform method=\"post\">\n    {% csrf_token %}\n    {{ form.as_p }}\n    \u003Cbutton type=\"submit\">Submit\u003C\u002Fbutton>\n\u003C\u002Fform>\n\n# AJAX requests\nfunction getCookie(name) {\n    let cookieValue = null;\n    if (document.cookie && document.cookie !== '') {\n        const cookies = document.cookie.split(';');\n        for (let i = 0; i \u003C cookies.length; i++) {\n            const cookie = cookies[i].trim();\n            if (cookie.substring(0, name.length + 1) === (name + '=')) {\n                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n                break;\n            }\n        }\n    }\n    return cookieValue;\n}\n\nfetch('\u002Fapi\u002Fendpoint\u002F', {\n    method: 'POST',\n    headers: {\n        'X-CSRFToken': getCookie('csrftoken'),\n        'Content-Type': 'application\u002Fjson',\n    },\n    body: JSON.stringify(data)\n});\n```\n\n### Exempting Views (Use Carefully)\n\n```python\nfrom django.views.decorators.csrf import csrf_exempt\n\n@csrf_exempt  # Only use when absolutely necessary!\ndef webhook_view(request):\n    # Webhook from external service\n    pass\n```\n\n## File Upload Security\n\n### File Validation\n\n```python\nimport os\nimport magic  # pip install python-magic\nfrom django.core.exceptions import ValidationError\n\nALLOWED_MIMES = {\n    'image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fgif', 'application\u002Fpdf',\n}\n\nMIME_TO_EXTENSIONS = {\n    'image\u002Fjpeg': {'.jpg', '.jpeg'},\n    'image\u002Fpng': {'.png'},\n    'image\u002Fgif': {'.gif'},\n    'application\u002Fpdf': {'.pdf'},\n}\n\ndef validate_file_type(value):\n    \"\"\"Validate file type using magic bytes and cross-check extension.\"\"\"\n    mime = magic.from_buffer(value.read(2048), mime=True)\n    value.seek(0)\n\n    if mime not in ALLOWED_MIMES:\n        raise ValidationError('Unsupported file type.')\n\n    ext = os.path.splitext(value.name)[1].lower()\n    if ext not in MIME_TO_EXTENSIONS.get(mime, set()):\n        raise ValidationError('File extension does not match file content.')\n\ndef validate_file_size(value):\n    \"\"\"Validate file size (max 5MB).\"\"\"\n    if value.size > 5 * 1024 * 1024:\n        raise ValidationError('File too large. Max size is 5MB.')\n\n# models.py\nclass Document(models.Model):\n    file = models.FileField(\n        upload_to='documents\u002F',\n        validators=[validate_file_type, validate_file_size]\n    )\n\n```\n\nFor environments where installing libmagic is difficult (e.g., minimal containers),\nuse the pure-Python `filetype` package as an alternative:\n\n```python\nimport os\nfrom django.core.exceptions import ValidationError\n\nimport filetype  # pip install filetype\n\nALLOWED_MIMES = {\n    'image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fgif', 'application\u002Fpdf',\n}\n\nMIME_TO_EXTENSIONS = {\n    'image\u002Fjpeg': {'.jpg', '.jpeg'},\n    'image\u002Fpng': {'.png'},\n    'image\u002Fgif': {'.gif'},\n    'application\u002Fpdf': {'.pdf'},\n}\n\ndef validate_file_type(value):\n    \"\"\"Validate file type using magic bytes.\"\"\"\n    kind = filetype.guess(value.read(2048))\n    value.seek(0)\n\n    if kind is None or kind.mime not in ALLOWED_MIMES:\n        raise ValidationError('Unsupported file type.')\n\n    ext = os.path.splitext(value.name)[1].lower()\n    if ext not in MIME_TO_EXTENSIONS.get(kind.mime, set()):\n        raise ValidationError('File extension does not match file content.')\n```\n\n### Secure File Storage\n\n```python\n# settings.py\nMEDIA_ROOT = '\u002Fvar\u002Fwww\u002Fmedia\u002F'\nMEDIA_URL = '\u002Fmedia\u002F'\n\n# Use a separate domain for media in production\nMEDIA_DOMAIN = 'https:\u002F\u002Fmedia.example.com'\n\n# Don't serve user uploads directly\n# Use whitenoise or a CDN for static files\n# Use a separate server or S3 for media files\n```\n\n## API Security\n\n### Rate Limiting\n\n```python\n# settings.py\nREST_FRAMEWORK = {\n    'DEFAULT_THROTTLE_CLASSES': [\n        'rest_framework.throttling.AnonRateThrottle',\n        'rest_framework.throttling.UserRateThrottle'\n    ],\n    'DEFAULT_THROTTLE_RATES': {\n        'anon': '100\u002Fday',\n        'user': '1000\u002Fday',\n        'upload': '10\u002Fhour',\n    }\n}\n\n# Custom throttle\nfrom rest_framework.throttling import UserRateThrottle\n\nclass BurstRateThrottle(UserRateThrottle):\n    scope = 'burst'\n    rate = '60\u002Fmin'\n\nclass SustainedRateThrottle(UserRateThrottle):\n    scope = 'sustained'\n    rate = '1000\u002Fday'\n```\n\n### Authentication for APIs\n\n```python\n# settings.py\nREST_FRAMEWORK = {\n    'DEFAULT_AUTHENTICATION_CLASSES': [\n        'rest_framework.authentication.TokenAuthentication',\n        'rest_framework.authentication.SessionAuthentication',\n        'rest_framework_simplejwt.authentication.JWTAuthentication',\n    ],\n    'DEFAULT_PERMISSION_CLASSES': [\n        'rest_framework.permissions.IsAuthenticated',\n    ],\n}\n\n# views.py\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\n\n@api_view(['GET', 'POST'])\n@permission_classes([IsAuthenticated])\ndef protected_view(request):\n    return Response({'message': 'You are authenticated'})\n```\n\n## Security Headers\n\n### Content Security Policy\n\n```python\n# settings.py\nCSP_DEFAULT_SRC = \"'self'\"\nCSP_SCRIPT_SRC = \"'self' https:\u002F\u002Fcdn.example.com\"\nCSP_STYLE_SRC = \"'self' 'unsafe-inline'\"\nCSP_IMG_SRC = \"'self' data: https:\"\nCSP_CONNECT_SRC = \"'self' https:\u002F\u002Fapi.example.com\"\n\n# Middleware\nclass CSPMiddleware:\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        response = self.get_response(request)\n        response['Content-Security-Policy'] = (\n            f\"default-src {CSP_DEFAULT_SRC}; \"\n            f\"script-src {CSP_SCRIPT_SRC}; \"\n            f\"style-src {CSP_STYLE_SRC}; \"\n            f\"img-src {CSP_IMG_SRC}; \"\n            f\"connect-src {CSP_CONNECT_SRC}\"\n        )\n        return response\n```\n\n## Environment Variables\n\n### Managing Secrets\n\n```python\n# Use python-decouple or django-environ\nimport environ\n\nenv = environ.Env(\n    # set casting, default value\n    DEBUG=(bool, False)\n)\n\n# reading .env file\nenviron.Env.read_env()\n\nSECRET_KEY = env('DJANGO_SECRET_KEY')\nDATABASE_URL = env('DATABASE_URL')\nALLOWED_HOSTS = env.list('ALLOWED_HOSTS')\n\n# .env file (never commit this)\nDEBUG=False\nSECRET_KEY=your-secret-key-here\nDATABASE_URL=postgresql:\u002F\u002Fuser:password@localhost:5432\u002Fdbname\nALLOWED_HOSTS=example.com,www.example.com\n```\n\n## Logging Security Events\n\n```python\n# settings.py\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'handlers': {\n        'file': {\n            'level': 'WARNING',\n            'class': 'logging.FileHandler',\n            'filename': '\u002Fvar\u002Flog\u002Fdjango\u002Fsecurity.log',\n        },\n        'console': {\n            'level': 'INFO',\n            'class': 'logging.StreamHandler',\n        },\n    },\n    'loggers': {\n        'django.security': {\n            'handlers': ['file', 'console'],\n            'level': 'WARNING',\n            'propagate': True,\n        },\n        'django.request': {\n            'handlers': ['file'],\n            'level': 'ERROR',\n            'propagate': False,\n        },\n    },\n}\n```\n\n## Quick Security Checklist\n\n| Check | Description |\n|-------|-------------|\n| `DEBUG = False` | Never run with DEBUG in production |\n| HTTPS only | Force SSL, secure cookies |\n| Strong secrets | Use environment variables for SECRET_KEY |\n| Password validation | Enable all password validators |\n| CSRF protection | Enabled by default, don't disable |\n| XSS prevention | Django auto-escapes, don't use `&#124;safe` with user input |\n| SQL injection | Use ORM, never concatenate strings in queries |\n| File uploads | Validate file type and size |\n| Rate limiting | Throttle API endpoints |\n| Security headers | CSP, X-Frame-Options, HSTS |\n| Logging | Log security events |\n| Updates | Keep Django and dependencies updated |\n\nRemember: Security is a process, not a product. Regularly review and update your security practices.\n","# Django Security Best Practices\n\nComprehensive security guidelines for Django applications to protect against common vulnerabilities.\n\n## When to Activate\n\n- Setting up Django authentication and authorization\n- Implementing user permissions and roles\n- Configuring production security settings\n- Reviewing Django application for security issues\n- Deploying Django applications to production\n\n## Core Security Settings\n\n### Production Settings Configuration\n\n```python\n# settings\u002Fproduction.py\nimport os\n\nDEBUG = False  # CRITICAL: Never use True in production\n\nALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')\n\n# Security headers\nSECURE_SSL_REDIRECT = True\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\nSECURE_HSTS_SECONDS = 31536000  # 1 year\nSECURE_HSTS_INCLUDE_SUBDOMAINS = True\nSECURE_HSTS_PRELOAD = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nX_FRAME_OPTIONS = 'DENY'\n\n# HTTPS and Cookies\nSESSION_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SAMESITE = 'Lax'\nCSRF_COOKIE_SAMESITE = 'Lax'\n\n# Secret key (must be set via environment variable)\nSECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')\nif not SECRET_KEY:\n    raise ImproperlyConfigured('DJANGO_SECRET_KEY environment variable is required')\n\n# Password validation\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n        'OPTIONS': {\n            'min_length': 12,\n        }\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n    },\n]\n```\n\n## Authentication\n\n### Custom User Model\n\n```python\n# apps\u002Fusers\u002Fmodels.py\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\nclass User(AbstractUser):\n    \"\"\"Custom user model for better security.\"\"\"\n\n    email = models.EmailField(unique=True)\n    phone = models.CharField(max_length=20, blank=True)\n\n    USERNAME_FIELD = 'email'  # Use email as username\n    REQUIRED_FIELDS = ['username']\n\n    class Meta:\n        db_table = 'users'\n        verbose_name = 'User'\n        verbose_name_plural = 'Users'\n\n    def __str__(self):\n        return self.email\n\n# settings\u002Fbase.py\nAUTH_USER_MODEL = 'users.User'\n```\n\n### Password Hashing\n\n```python\n# Django uses PBKDF2 by default. For stronger security:\nPASSWORD_HASHERS = [\n    'django.contrib.auth.hashers.Argon2PasswordHasher',\n    'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n]\n```\n\n### Session Management\n\n```python\n# Session configuration\nSESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # Or 'db'\nSESSION_CACHE_ALIAS = 'default'\nSESSION_COOKIE_AGE = 3600 * 24 * 7  # 1 week\nSESSION_SAVE_EVERY_REQUEST = False\nSESSION_EXPIRE_AT_BROWSER_CLOSE = False  # Better UX, but less secure\n```\n\n## Authorization\n\n### Permissions\n\n```python\n# models.py\nfrom django.db import models\nfrom django.contrib.auth.models import Permission\n\nclass Post(models.Model):\n    title = models.CharField(max_length=200)\n    content = models.TextField()\n    author = models.ForeignKey(User, on_delete=models.CASCADE)\n\n    class Meta:\n        permissions = [\n            ('can_publish', 'Can publish posts'),\n            ('can_edit_others', 'Can edit posts of others'),\n        ]\n\n    def user_can_edit(self, user):\n        \"\"\"Check if user can edit this post.\"\"\"\n        return self.author == user or user.has_perm('app.can_edit_others')\n\n# views.py\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.views.generic import UpdateView\n\nclass PostUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n    model = Post\n    permission_required = 'app.can_edit_others'\n    raise_exception = True  # Return 403 instead of redirect\n\n    def get_queryset(self):\n        \"\"\"Only allow users to edit their own posts.\"\"\"\n        return Post.objects.filter(author=self.request.user)\n```\n\n### Custom Permissions\n\n```python\n# permissions.py\nfrom rest_framework import permissions\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n    \"\"\"Allow only owners to edit objects.\"\"\"\n\n    def has_object_permission(self, request, view, obj):\n        # Read permissions allowed for any request\n        if request.method in permissions.SAFE_METHODS:\n            return True\n\n        # Write permissions only for owner\n        return obj.author == request.user\n\nclass IsAdminOrReadOnly(permissions.BasePermission):\n    \"\"\"Allow admins to do anything, others read-only.\"\"\"\n\n    def has_permission(self, request, view):\n        if request.method in permissions.SAFE_METHODS:\n            return True\n        return request.user and request.user.is_staff\n\nclass IsVerifiedUser(permissions.BasePermission):\n    \"\"\"Allow only verified users.\"\"\"\n\n    def has_permission(self, request, view):\n        return request.user and request.user.is_authenticated and request.user.is_verified\n```\n\n### Role-Based Access Control (RBAC)\n\n```python\n# models.py\nfrom django.contrib.auth.models import AbstractUser, Group\n\nclass User(AbstractUser):\n    ROLE_CHOICES = [\n        ('admin', 'Administrator'),\n        ('moderator', 'Moderator'),\n        ('user', 'Regular User'),\n    ]\n    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='user')\n\n    def is_admin(self):\n        return self.role == 'admin' or self.is_superuser\n\n    def is_moderator(self):\n        return self.role in ['admin', 'moderator']\n\n# Mixins\nclass AdminRequiredMixin:\n    \"\"\"Mixin to require admin role.\"\"\"\n\n    def dispatch(self, request, *args, **kwargs):\n        if not request.user.is_authenticated or not request.user.is_admin():\n            from django.core.exceptions import PermissionDenied\n            raise PermissionDenied\n        return super().dispatch(request, *args, **kwargs)\n```\n\n## SQL Injection Prevention\n\n### Django ORM Protection\n\n```python\n# GOOD: Django ORM automatically escapes parameters\ndef get_user(username):\n    return User.objects.get(username=username)  # Safe\n\n# GOOD: Using parameters with raw()\ndef search_users(query):\n    return User.objects.raw('SELECT * FROM users WHERE username = %s', [query])\n\n# BAD: Never directly interpolate user input\ndef get_user_bad(username):\n    return User.objects.raw(f'SELECT * FROM users WHERE username = {username}')  # VULNERABLE!\n\n# GOOD: Using filter with proper escaping\ndef get_users_by_email(email):\n    return User.objects.filter(email__iexact=email)  # Safe\n\n# GOOD: Using Q objects for complex queries\nfrom django.db.models import Q\ndef search_users_complex(query):\n    return User.objects.filter(\n        Q(username__icontains=query) |\n        Q(email__icontains=query)\n    )  # Safe\n```\n\n### Extra Security with raw()\n\n```python\n# If you must use raw SQL, always use parameters\nUser.objects.raw(\n    'SELECT * FROM users WHERE email = %s AND status = %s',\n    [user_input_email, status]\n)\n```\n\n## XSS Prevention\n\n### Template Escaping\n\n```django\n{# Django auto-escapes variables by default - SAFE #}\n{{ user_input }}  {# Escaped HTML #}\n\n{# Explicitly mark safe only for trusted content #}\n{{ trusted_html|safe }}  {# Not escaped #}\n\n{# Use template filters for safe HTML #}\n{{ user_input|escape }}  {# Same as default #}\n{{ user_input|striptags }}  {# Remove all HTML tags #}\n\n{# JavaScript escaping #}\n\u003Cscript>\n    var username = {{ username|escapejs }};\n\u003C\u002Fscript>\n```\n\n### Safe String Handling\n\n```python\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import escape\n\n# BAD: Never mark user input as safe without escaping\ndef render_bad(user_input):\n    return mark_safe(user_input)  # VULNERABLE!\n\n# GOOD: Escape first, then mark safe\ndef render_good(user_input):\n    return mark_safe(escape(user_input))\n\n# GOOD: Use format_html for HTML with variables\nfrom django.utils.html import format_html\n\ndef greet_user(username):\n    return format_html('\u003Cspan class=\"user\">{}\u003C\u002Fspan>', escape(username))\n```\n\n### HTTP Headers\n\n```python\n# settings.py\nSECURE_CONTENT_TYPE_NOSNIFF = True  # Prevent MIME sniffing\nX_FRAME_OPTIONS = 'DENY'  # Prevent clickjacking\n\n# Custom middleware\nfrom django.conf import settings\n\nclass SecurityHeaderMiddleware:\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        response = self.get_response(request)\n        response['X-Content-Type-Options'] = 'nosniff'\n        response['X-Frame-Options'] = 'DENY'\n        response['X-XSS-Protection'] = '1; mode=block'\n        response['Content-Security-Policy'] = \"default-src 'self'\"\n        return response\n```\n\n## CSRF Protection\n\n### Default CSRF Protection\n\n```python\n# settings.py - CSRF is enabled by default\nCSRF_COOKIE_SECURE = True  # Only send over HTTPS\nCSRF_COOKIE_HTTPONLY = False  # False so AJAX can read csrf token from document.cookie; SESSION_COOKIE_HTTPONLY remains True\nCSRF_COOKIE_SAMESITE = 'Lax'  # Prevent CSRF in some cases\nCSRF_TRUSTED_ORIGINS = ['https:\u002F\u002Fexample.com']  # Trusted domains\n\n# Template usage\n\u003Cform method=\"post\">\n    {% csrf_token %}\n    {{ form.as_p }}\n    \u003Cbutton type=\"submit\">Submit\u003C\u002Fbutton>\n\u003C\u002Fform>\n\n# AJAX requests\nfunction getCookie(name) {\n    let cookieValue = null;\n    if (document.cookie && document.cookie !== '') {\n        const cookies = document.cookie.split(';');\n        for (let i = 0; i \u003C cookies.length; i++) {\n            const cookie = cookies[i].trim();\n            if (cookie.substring(0, name.length + 1) === (name + '=')) {\n                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n                break;\n            }\n        }\n    }\n    return cookieValue;\n}\n\nfetch('\u002Fapi\u002Fendpoint\u002F', {\n    method: 'POST',\n    headers: {\n        'X-CSRFToken': getCookie('csrftoken'),\n        'Content-Type': 'application\u002Fjson',\n    },\n    body: JSON.stringify(data)\n});\n```\n\n### Exempting Views (Use Carefully)\n\n```python\nfrom django.views.decorators.csrf import csrf_exempt\n\n@csrf_exempt  # Only use when absolutely necessary!\ndef webhook_view(request):\n    # Webhook from external service\n    pass\n```\n\n## File Upload Security\n\n### File Validation\n\n```python\nimport os\nimport magic  # pip install python-magic\nfrom django.core.exceptions import ValidationError\n\nALLOWED_MIMES = {\n    'image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fgif', 'application\u002Fpdf',\n}\n\nMIME_TO_EXTENSIONS = {\n    'image\u002Fjpeg': {'.jpg', '.jpeg'},\n    'image\u002Fpng': {'.png'},\n    'image\u002Fgif': {'.gif'},\n    'application\u002Fpdf': {'.pdf'},\n}\n\ndef validate_file_type(value):\n    \"\"\"Validate file type using magic bytes and cross-check extension.\"\"\"\n    mime = magic.from_buffer(value.read(2048), mime=True)\n    value.seek(0)\n\n    if mime not in ALLOWED_MIMES:\n        raise ValidationError('Unsupported file type.')\n\n    ext = os.path.splitext(value.name)[1].lower()\n    if ext not in MIME_TO_EXTENSIONS.get(mime, set()):\n        raise ValidationError('File extension does not match file content.')\n\ndef validate_file_size(value):\n    \"\"\"Validate file size (max 5MB).\"\"\"\n    if value.size > 5 * 1024 * 1024:\n        raise ValidationError('File too large. Max size is 5MB.')\n\n# models.py\nclass Document(models.Model):\n    file = models.FileField(\n        upload_to='documents\u002F',\n        validators=[validate_file_type, validate_file_size]\n    )\n\n```\n\nFor environments where installing libmagic is difficult (e.g., minimal containers),\nuse the pure-Python `filetype` package as an alternative:\n\n```python\nimport os\nfrom django.core.exceptions import ValidationError\n\nimport filetype  # pip install filetype\n\nALLOWED_MIMES = {\n    'image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fgif', 'application\u002Fpdf',\n}\n\nMIME_TO_EXTENSIONS = {\n    'image\u002Fjpeg': {'.jpg', '.jpeg'},\n    'image\u002Fpng': {'.png'},\n    'image\u002Fgif': {'.gif'},\n    'application\u002Fpdf': {'.pdf'},\n}\n\ndef validate_file_type(value):\n    \"\"\"Validate file type using magic bytes.\"\"\"\n    kind = filetype.guess(value.read(2048))\n    value.seek(0)\n\n    if kind is None or kind.mime not in ALLOWED_MIMES:\n        raise ValidationError('Unsupported file type.')\n\n    ext = os.path.splitext(value.name)[1].lower()\n    if ext not in MIME_TO_EXTENSIONS.get(kind.mime, set()):\n        raise ValidationError('File extension does not match file content.')\n```\n\n### Secure File Storage\n\n```python\n# settings.py\nMEDIA_ROOT = '\u002Fvar\u002Fwww\u002Fmedia\u002F'\nMEDIA_URL = '\u002Fmedia\u002F'\n\n# Use a separate domain for media in production\nMEDIA_DOMAIN = 'https:\u002F\u002Fmedia.example.com'\n\n# Don't serve user uploads directly\n# Use whitenoise or a CDN for static files\n# Use a separate server or S3 for media files\n```\n\n## API Security\n\n### Rate Limiting\n\n```python\n# settings.py\nREST_FRAMEWORK = {\n    'DEFAULT_THROTTLE_CLASSES': [\n        'rest_framework.throttling.AnonRateThrottle',\n        'rest_framework.throttling.UserRateThrottle'\n    ],\n    'DEFAULT_THROTTLE_RATES': {\n        'anon': '100\u002Fday',\n        'user': '1000\u002Fday',\n        'upload': '10\u002Fhour',\n    }\n}\n\n# Custom throttle\nfrom rest_framework.throttling import UserRateThrottle\n\nclass BurstRateThrottle(UserRateThrottle):\n    scope = 'burst'\n    rate = '60\u002Fmin'\n\nclass SustainedRateThrottle(UserRateThrottle):\n    scope = 'sustained'\n    rate = '1000\u002Fday'\n```\n\n### Authentication for APIs\n\n```python\n# settings.py\nREST_FRAMEWORK = {\n    'DEFAULT_AUTHENTICATION_CLASSES': [\n        'rest_framework.authentication.TokenAuthentication',\n        'rest_framework.authentication.SessionAuthentication',\n        'rest_framework_simplejwt.authentication.JWTAuthentication',\n    ],\n    'DEFAULT_PERMISSION_CLASSES': [\n        'rest_framework.permissions.IsAuthenticated',\n    ],\n}\n\n# views.py\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\n\n@api_view(['GET', 'POST'])\n@permission_classes([IsAuthenticated])\ndef protected_view(request):\n    return Response({'message': 'You are authenticated'})\n```\n\n## Security Headers\n\n### Content Security Policy\n\n```python\n# settings.py\nCSP_DEFAULT_SRC = \"'self'\"\nCSP_SCRIPT_SRC = \"'self' https:\u002F\u002Fcdn.example.com\"\nCSP_STYLE_SRC = \"'self' 'unsafe-inline'\"\nCSP_IMG_SRC = \"'self' data: https:\"\nCSP_CONNECT_SRC = \"'self' https:\u002F\u002Fapi.example.com\"\n\n# Middleware\nclass CSPMiddleware:\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        response = self.get_response(request)\n        response['Content-Security-Policy'] = (\n            f\"default-src {CSP_DEFAULT_SRC}; \"\n            f\"script-src {CSP_SCRIPT_SRC}; \"\n            f\"style-src {CSP_STYLE_SRC}; \"\n            f\"img-src {CSP_IMG_SRC}; \"\n            f\"connect-src {CSP_CONNECT_SRC}\"\n        )\n        return response\n```\n\n## Environment Variables\n\n### Managing Secrets\n\n```python\n# Use python-decouple or django-environ\nimport environ\n\nenv = environ.Env(\n    # set casting, default value\n    DEBUG=(bool, False)\n)\n\n# reading .env file\nenviron.Env.read_env()\n\nSECRET_KEY = env('DJANGO_SECRET_KEY')\nDATABASE_URL = env('DATABASE_URL')\nALLOWED_HOSTS = env.list('ALLOWED_HOSTS')\n\n# .env file (never commit this)\nDEBUG=False\nSECRET_KEY=your-secret-key-here\nDATABASE_URL=postgresql:\u002F\u002Fuser:password@localhost:5432\u002Fdbname\nALLOWED_HOSTS=example.com,www.example.com\n```\n\n## Logging Security Events\n\n```python\n# settings.py\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'handlers': {\n        'file': {\n            'level': 'WARNING',\n            'class': 'logging.FileHandler',\n            'filename': '\u002Fvar\u002Flog\u002Fdjango\u002Fsecurity.log',\n        },\n        'console': {\n            'level': 'INFO',\n            'class': 'logging.StreamHandler',\n        },\n    },\n    'loggers': {\n        'django.security': {\n            'handlers': ['file', 'console'],\n            'level': 'WARNING',\n            'propagate': True,\n        },\n        'django.request': {\n            'handlers': ['file'],\n            'level': 'ERROR',\n            'propagate': False,\n        },\n    },\n}\n```\n\n## Quick Security Checklist\n\n| Check | Description |\n|-------|-------------|\n| `DEBUG = False` | Never run with DEBUG in production |\n| HTTPS only | Force SSL, secure cookies |\n| Strong secrets | Use environment variables for SECRET_KEY |\n| Password validation | Enable all password validators |\n| CSRF protection | Enabled by default, don't disable |\n| XSS prevention | Django auto-escapes, don't use `&#124;safe` with user input |\n| SQL injection | Use ORM, never concatenate strings in queries |\n| File uploads | Validate file type and size |\n| Rate limiting | Throttle API endpoints |\n| Security headers | CSP, X-Frame-Options, HSTS |\n| Logging | Log security events |\n| Updates | Keep Django and dependencies updated |\n\nRemember: Security is a process, not a product. Regularly review and update your security practices.\n",{"name":5,"metadata":23,"description":7},{"origin":24},"ECC","main","7542b2fc80051758dfb288b450cb344d3bdfca35","curation\u002Fskills\u002Fdjango-security",0,"https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified","https:\u002F\u002Fgithub.com\u002FMoradDev","2026-11-07 21:53:24",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add MoradDev\u002Fskills-unified --skill django-security",{"tool":38,"command":39},"bunx","bunx skills add MoradDev\u002Fskills-unified --skill django-security",{"tool":41,"command":42},"pnpm","pnpm dlx skills add MoradDev\u002Fskills-unified --skill django-security","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fdjango-security\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":18},"01M7DB9J6N2PSGECQ6FTWW7B2H","windows-desktop-e2e","E2E testing for Windows native desktop apps (WPF, WinForms, Win32\u002FMFC, Qt) using pywinauto and Windows UI Automation. Use when writing E2E tests for a Windows native desktop app with pywinauto or UI Automation.","https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fwindows-desktop-e2e\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":18},"01M7DB9CCWT4YW7B791QN43E3Q","vue-patterns","Vue.js 3 Composition API patterns, component architecture, reactivity best practices, Pinia state management, Vue Router navigation, and Nuxt SSR patterns. Activates for Vue, Nuxt, Vite, or Pinia projects. Use when building or reviewing Vue 3, Nuxt, or Pinia code — Composition API, reactivity, or router navigation.","https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fvue-patterns\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7DB976FM2CAWT807EA36MXM","vite-patterns","Vite build tool patterns including config, plugins, HMR, env variables, proxy setup, SSR, library mode, dependency pre-bundling, and build optimization. Activate when working with vite.config.ts, Vite plugins, or Vite-based projects.","https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fvite-patterns\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":18},"01M7DB93JZRAWFB5QHH0C8DZ8N","using-agent-skills","Discovers and invokes agent skills. Use when starting a session, or when you need to decide which skill or workflow applies to the piece of work at hand. This is the meta-skill that governs how all other skills are discovered and invoked.","https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fusing-agent-skills\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":18},"01M7DB8YYW1PEDS7H2AA86TE2E","ui-demo","Record polished UI demo videos using Playwright. Use when the user asks to create a demo, walkthrough, screen recording, or tutorial video of a web application. Produces WebM videos with visible cursor, natural pacing, and professional feel.","https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fui-demo\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":18},"01M7DB8RPQPW2R6GKJW618VDST","swiftui-patterns","SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS\u002FmacOS UI best practices. Use when building or reviewing SwiftUI views, @Observable state, navigation, or render performance.","https:\u002F\u002Fgithub.com\u002FMoradDev\u002Fskills-unified\u002Fblob\u002Fmain\u002Fcuration\u002Fskills\u002Fswiftui-patterns\u002FSKILL.md",[],[]]