SwiftAcademy Logo

Navigation

Django Security Best Practices: Protect Your Web Application from Common Attacks

Published Apr 08 2026Updated Mar 22 2026
Django Security Best Practices: Protect Your Web Application from Common Attacks

Django is known as "the web framework for perfectionists with deadlines," and one of its strongest selling points is built-in security. But "built-in" does not mean "automatic." Developers who do not understand Django security best practices regularly ship applications with vulnerabilities that expose user data, allow unauthorized access, or enable attackers to take control of entire systems. In Nepal's growing tech scene, where startups and agencies are building applications for banking, e-commerce, and healthcare, security is not optional — it is a professional obligation.

This guide covers the most critical Django security practices with real code examples, configuration snippets, and deployment checklists. Whether you are building a project for a Nepali client, preparing for a job interview, or deploying your first Django app, these practices will protect your application from the attacks that actually happen in the real world.

Pillar Page: Python Django Full Stack Course at Swift Academy


What Are the Most Common Security Threats to Django Applications?

The most common attacks targeting Django applications are Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), SQL injection, clickjacking, and insecure authentication — Django provides built-in protection for all of these, but developers must configure and use them correctly. Here is what each attack does:

Attack Type What It Does Django's Built-in Protection Your Responsibility
XSS Injects malicious scripts into pages Auto-escaping in templates Don't use `
CSRF Tricks users into making unwanted requests CSRF middleware + tokens Include {% csrf_token %} in forms
SQL Injection Manipulates database queries ORM parameterization Don't use raw SQL without parameters
Clickjacking Embeds your site in a hidden iframe X-Frame-Options middleware Keep middleware enabled
Authentication Bypass Gains unauthorized access Auth framework + permissions Use proper authentication backends
Data Exposure Leaks sensitive information DEBUG=False in production Configure settings properly

The OWASP Top 10 and Django

The Open Web Application Security Project (OWASP) Top 10 lists the most critical web application security risks. Django addresses most of them out of the box:

  1. Injection — Django ORM prevents SQL injection by default
  2. Broken Authentication — Django's auth system handles password hashing, session management
  3. Sensitive Data Exposure — Settings for HTTPS, secure cookies
  4. XML External Entities — Not typically relevant to Django
  5. Broken Access Control — Permission decorators and mixins
  6. Security Misconfiguration — Deployment checklist (manage.py check --deploy)
  7. Cross-Site Scripting (XSS) — Template auto-escaping
  8. Insecure Deserialization — Avoid using pickle with user data
  9. Using Components with Known Vulnerabilities — Keep dependencies updated
  10. Insufficient Logging — Django's logging framework

How Do I Protect My Django Application from XSS Attacks?

Django protects against XSS by automatically escaping all template variables, but developers bypass this protection when they use the |safe filter, mark_safe(), or {% autoescape off %} — so the key practice is to never mark user-supplied content as safe. Here is how to do it right:

What XSS Does

An attacker injects JavaScript into your page through user input. When other users view that page, the malicious script executes in their browser, potentially stealing cookies, session tokens, or personal data.

Django's Auto-Escaping

# In your view
def profile(request):
    user_bio = '<script>alert("hacked")</script>'
    return render(request, 'profile.html', {'bio': user_bio})
<!-- Template: profile.html -->
<!-- SAFE: Django auto-escapes this -->
<p>{{ bio }}</p>
<!-- Renders as: &lt;script&gt;alert(&quot;hacked&quot;)&lt;/script&gt; -->
<!-- The script does NOT execute -->

<!-- DANGEROUS: |safe disables escaping -->
<p>{{ bio|safe }}</p>
<!-- Renders as: <script>alert("hacked")</script> -->
<!-- The script EXECUTES! -->

Rules for XSS Prevention

# NEVER do this with user input
from django.utils.safestring import mark_safe

def display_comment(request):
    comment = request.POST.get('comment')  # User-controlled input!
    safe_comment = mark_safe(comment)  # DANGEROUS - never mark user input as safe
    return render(request, 'comment.html', {'comment': safe_comment})

# DO this instead - sanitize if you need HTML
import bleach

def display_comment(request):
    comment = request.POST.get('comment')
    # Only allow specific safe HTML tags
    clean_comment = bleach.clean(
        comment,
        tags=['b', 'i', 'u', 'p', 'br', 'a'],
        attributes={'a': ['href', 'title']},
        strip=True
    )
    return render(request, 'comment.html', {'comment': clean_comment})

Content Security Policy Header

Add CSP headers to prevent inline script execution:

# settings.py - using django-csp package
CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'", "https://cdn.example.com")
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'")  # Avoid unsafe-inline if possible
CSP_IMG_SRC = ("'self'", "data:", "https:")

# Or manually in middleware
class CSPMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['Content-Security-Policy'] = "default-src 'self'; script-src 'self'"
        return response

How Do I Properly Implement CSRF Protection in Django?

Django's CSRF protection is enabled by default through the CsrfViewMiddleware, but it only works when you include {% csrf_token %} in every POST form and properly handle CSRF tokens in AJAX requests — skipping this is the most common CSRF mistake in Nepali Django projects. Here is the complete implementation:

For HTML Forms

<!-- CORRECT: Always include csrf_token in POST forms -->
<form method="post" action="{% url 'submit_order' %}">
    {% csrf_token %}
    <input type="text" name="product" value="Laptop">
    <input type="number" name="quantity" value="1">
    <button type="submit">Order</button>
</form>

<!-- WRONG: Missing csrf_token - will get 403 Forbidden -->
<form method="post" action="{% url 'submit_order' %}">
    <input type="text" name="product" value="Laptop">
    <button type="submit">Order</button>
</form>

For AJAX Requests (JavaScript)

// Get CSRF token from cookie
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// Include in AJAX requests
fetch('/api/order/', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken'),  // Required for POST/PUT/DELETE
    },
    body: JSON.stringify({ product: 'Laptop', quantity: 1 }),
});

For Django REST Framework APIs

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',  # Uses CSRF
        'rest_framework.authentication.TokenAuthentication',     # No CSRF needed
    ],
}

# For token-based APIs, CSRF is not needed because the token itself is the authentication
# For session-based APIs, CSRF is required

Common CSRF Mistakes to Avoid

# NEVER do this in production
@csrf_exempt  # Disables CSRF protection for this view
def process_payment(request):
    # This endpoint is now vulnerable to CSRF attacks!
    pass

# If you need to exempt an API endpoint, use token authentication instead
from rest_framework.decorators import api_view, authentication_classes
from rest_framework.authentication import TokenAuthentication

@api_view(['POST'])
@authentication_classes([TokenAuthentication])
def process_payment(request):
    # Token auth provides its own protection
    pass

How Do I Prevent SQL Injection in Django?

Django's ORM prevents SQL injection by parameterizing all queries automatically, but developers introduce vulnerabilities when they use raw(), extra(), or string formatting to build queries — always use parameterized queries even when writing raw SQL. Here are the safe and unsafe patterns:

Safe: Using Django ORM

# SAFE: ORM handles parameterization
from myapp.models import Product

# Filter - safe
products = Product.objects.filter(name=user_input)

# Lookup - safe
product = Product.objects.get(pk=product_id)

# Q objects - safe
from django.db.models import Q
results = Product.objects.filter(
    Q(name__icontains=search_term) | Q(description__icontains=search_term)
)

Dangerous: Raw SQL Without Parameters

# DANGEROUS: String formatting with user input
def search_products(request):
    query = request.GET.get('q')

    # NEVER do this - SQL injection vulnerability!
    products = Product.objects.raw(
        f"SELECT * FROM products WHERE name = '{query}'"
    )
    # Attacker input: ' OR '1'='1' --
    # Results in: SELECT * FROM products WHERE name = '' OR '1'='1' --'
    # Returns ALL products!

    # SAFE: Use parameterized queries
    products = Product.objects.raw(
        "SELECT * FROM products WHERE name = %s", [query]
    )
    # The %s is safely parameterized - no injection possible

Safe Raw SQL Patterns

from django.db import connection

# SAFE: Parameterized raw query
def get_products_by_category(category_name):
    with connection.cursor() as cursor:
        cursor.execute(
            "SELECT id, name, price FROM products WHERE category = %s ORDER BY price",
            [category_name]  # Parameters passed as a list
        )
        return cursor.fetchall()

# SAFE: Using params with extra() - though extra() is deprecated
# Better to use ORM or raw() with parameters

How Should I Configure Django Settings for Production Security?

Your Django production settings must disable DEBUG mode, set ALLOWED_HOSTS, enforce HTTPS, configure secure cookies, and set proper security headers — running Django's built-in security checker (python manage.py check --deploy) catches most configuration mistakes. Here is a production-ready security configuration:

Essential Production Settings

# settings/production.py

import os

# CRITICAL: Never True in production
DEBUG = False

# CRITICAL: Restrict to your actual domains
ALLOWED_HOSTS = ['yourdomain.com.np', 'www.yourdomain.com.np']

# Secret key from environment variable - never hardcode
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

# HTTPS Settings
SECURE_SSL_REDIRECT = True  # Redirect HTTP to HTTPS
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Cookie Security
SESSION_COOKIE_SECURE = True      # Only send over HTTPS
CSRF_COOKIE_SECURE = True         # Only send over HTTPS
SESSION_COOKIE_HTTPONLY = True     # JavaScript can't access session cookie
CSRF_COOKIE_HTTPONLY = True        # JavaScript can't access CSRF cookie (use header method instead)

# Security Headers
SECURE_BROWSER_XSS_FILTER = True          # X-XSS-Protection header
SECURE_CONTENT_TYPE_NOSNIFF = True        # X-Content-Type-Options: nosniff
X_FRAME_OPTIONS = 'DENY'                  # Prevent clickjacking
SECURE_HSTS_SECONDS = 31536000            # HSTS - 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True     # HSTS for subdomains
SECURE_HSTS_PRELOAD = True                # HSTS preload list

# Password Validators
AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
     'OPTIONS': {'min_length': 10}},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]

# Session Security
SESSION_COOKIE_AGE = 3600          # 1 hour session timeout
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True  # Extend session on activity

# File Upload Security
FILE_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024  # 5MB max
DATA_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024

Running the Security Checker

python manage.py check --deploy

This command checks for common security misconfigurations and outputs warnings like:

?(security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting.
?(security.W008) Your SECURE_SSL_REDIRECT setting is not set to True.
?(security.W012) SESSION_COOKIE_SECURE is not set to True.

Fix all warnings before deploying to production.

Environment Variables for Secrets

# NEVER do this
SECRET_KEY = 'django-insecure-abc123def456'
DATABASE_PASSWORD = 'mypassword123'

# DO this - use environment variables
import os
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']

# Or use django-environ
import environ
env = environ.Env()
environ.Env.read_env('.env')

SECRET_KEY = env('DJANGO_SECRET_KEY')
DATABASE_URL = env('DATABASE_URL')

How Do I Implement Secure Authentication and Authorization?

Secure authentication in Django requires proper password hashing (use Django's built-in hashers), rate limiting on login attempts, two-factor authentication for sensitive applications, and role-based access control using Django's permission system. Here is how to implement each:

Secure User Registration

# views.py
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError

def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')

        # Validate password strength
        try:
            validate_password(password)
        except ValidationError as e:
            return render(request, 'register.html', {'errors': e.messages})

        # Check for existing user
        if User.objects.filter(username=username).exists():
            return render(request, 'register.html', {'errors': ['Username already exists']})

        # Create user - password is automatically hashed
        user = User.objects.create_user(
            username=username,
            password=password,  # Django hashes this with PBKDF2 by default
            email=email,
        )
        return redirect('login')

Rate Limiting Login Attempts

# Using django-axes for brute force protection
# pip install django-axes

# settings.py
INSTALLED_APPS = [
    # ...
    'axes',
]

MIDDLEWARE = [
    # ...
    'axes.middleware.AxesMiddleware',
]

AUTHENTICATION_BACKENDS = [
    'axes.backends.AxesStandaloneBackend',
    'django.contrib.auth.backends.ModelBackend',
]

# Configuration
AXES_FAILURE_LIMIT = 5              # Lock after 5 failed attempts
AXES_COOLOFF_TIME = 1               # Lock for 1 hour
AXES_LOCKOUT_CALLABLE = 'myapp.views.lockout_response'
AXES_RESET_ON_SUCCESS = True        # Reset counter on successful login

Permission-Based Access Control

# views.py
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin

# Function-based views
@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

@permission_required('products.can_edit_price', raise_exception=True)
def edit_price(request, product_id):
    # Only users with 'can_edit_price' permission can access
    pass

# Class-based views
class AdminDashboard(LoginRequiredMixin, PermissionRequiredMixin, View):
    permission_required = 'admin.view_dashboard'
    login_url = '/login/'

    def get(self, request):
        return render(request, 'admin_dashboard.html')

Secure Password Reset

# urls.py - Use Django's built-in password reset views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('password-reset/',
         auth_views.PasswordResetView.as_view(
             template_name='registration/password_reset.html',
             email_template_name='registration/password_reset_email.html',
             success_url='/password-reset/done/',
         ),
         name='password_reset'),
    path('password-reset/confirm/<uidb64>/<token>/',
         auth_views.PasswordResetConfirmView.as_view(),
         name='password_reset_confirm'),
]

What Security Measures Should I Take When Deploying Django?

Django deployment security requires HTTPS enforcement, proper web server configuration (Nginx/Gunicorn), database security, static file handling through a CDN or web server (never Django), and regular dependency updates to patch known vulnerabilities. Here is a deployment security checklist:

Deployment Architecture

Client (HTTPS) → Nginx (reverse proxy) → Gunicorn (WSGI) → Django App → PostgreSQL
                    ↓
              Static Files (served by Nginx, not Django)

Nginx Security Configuration

server {
    listen 443 ssl;
    server_name yourdomain.com.np;

    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/yourdomain.com.np/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com.np/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    # Security Headers
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # Limit request size
    client_max_body_size 10M;

    # Serve static files directly (not through Django)
    location /static/ {
        alias /var/www/yourdomain/static/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    location /media/ {
        alias /var/www/yourdomain/media/;
        expires 7d;
    }

    # Proxy to Gunicorn
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name yourdomain.com.np;
    return 301 https://$server_name$request_uri;
}

Database Security

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASSWORD'],
        'HOST': os.environ['DB_HOST'],
        'PORT': '5432',
        'OPTIONS': {
            'sslmode': 'require',  # Encrypt database connections
        },
    }
}

Keeping Dependencies Updated

# Check for security vulnerabilities in dependencies
pip install safety
safety check

# Or use pip-audit
pip install pip-audit
pip-audit

# Update requirements regularly
pip install --upgrade django
pip freeze > requirements.txt

How Do I Handle File Uploads Securely in Django?

Secure file uploads require validating file types by content (not just extension), limiting file sizes, storing uploaded files outside the web root, scanning for malware in sensitive applications, and never executing uploaded files. Here is the safe approach:

Secure File Upload Implementation

# models.py
import os
import uuid
from django.db import models
from django.core.exceptions import ValidationError

def validate_file_extension(value):
    """Validate file extension against whitelist."""
    allowed_extensions = ['.pdf', '.jpg', '.jpeg', '.png', '.doc', '.docx']
    ext = os.path.splitext(value.name)[1].lower()
    if ext not in allowed_extensions:
        raise ValidationError(f'File type {ext} is not allowed.')

def validate_file_size(value):
    """Limit file size to 5MB."""
    limit = 5 * 1024 * 1024  # 5MB
    if value.size > limit:
        raise ValidationError('File size must not exceed 5MB.')

def user_upload_path(instance, filename):
    """Generate unique filename to prevent overwriting and path traversal."""
    ext = os.path.splitext(filename)[1]
    unique_name = f"{uuid.uuid4().hex}{ext}"
    return f"uploads/{instance.user.id}/{unique_name}"

class Document(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    file = models.FileField(
        upload_to=user_upload_path,
        validators=[validate_file_extension, validate_file_size],
    )
    uploaded_at = models.DateTimeField(auto_now_add=True)
# views.py
from django.contrib.auth.decorators import login_required
import magic  # python-magic library for content-type validation

@login_required
def upload_document(request):
    if request.method == 'POST' and request.FILES.get('file'):
        uploaded_file = request.FILES['file']

        # Validate content type (not just extension)
        file_type = magic.from_buffer(uploaded_file.read(1024), mime=True)
        uploaded_file.seek(0)  # Reset file pointer

        allowed_types = ['application/pdf', 'image/jpeg', 'image/png']
        if file_type not in allowed_types:
            return render(request, 'upload.html', {'error': 'Invalid file type'})

        doc = Document(user=request.user, file=uploaded_file)
        doc.full_clean()  # Runs model validators
        doc.save()
        return redirect('documents')

What Does Reddit Say About Django Security?

The Django and security communities on Reddit offer practical wisdom:

  • r/django — "Run manage.py check --deploy before every deployment. It catches 80% of security misconfigurations that developers forget. Takes 2 seconds, saves you from embarrassing breaches." (Top advice, 2025)

  • r/django — "The biggest security mistake I see in Django projects from South Asian outsourcing companies: DEBUG=True in production and SECRET_KEY committed to Git. These are basics, but they happen constantly."

  • r/netsec — "Django's security features are excellent out of the box, but they only protect you if you don't bypass them. Every @csrf_exempt and |safe in your codebase is a potential vulnerability."

  • r/webdev — "For anyone deploying Django for the first time: use Let's Encrypt for free SSL, put Nginx in front of Gunicorn, and never serve static files through Django in production."


Practical Takeaway: Django Security Checklist

Use this checklist before deploying any Django application:

Before First Deployment:

  • DEBUG = False
  • SECRET_KEY loaded from environment variable
  • ALLOWED_HOSTS set to actual domains only
  • SECURE_SSL_REDIRECT = True
  • All cookie security settings enabled
  • HSTS headers configured
  • python manage.py check --deploy passes with no warnings
  • Database credentials in environment variables
  • Password validators configured
  • File upload validation in place

Ongoing Security:

  • Dependencies updated monthly (pip-audit)
  • Django version kept current (security patches)
  • Access logs monitored
  • Brute force protection active (django-axes)
  • Backup strategy tested
  • Error reporting configured (Sentry or similar)

Code Review Checklist:

  • No @csrf_exempt without justification
  • No |safe filter on user input
  • No raw SQL with string formatting
  • No hardcoded secrets in code
  • Proper authentication on all protected views
  • Input validation on all forms

Frequently Asked Questions

Is Django secure by default?

Django provides excellent default security including CSRF protection, XSS prevention through template auto-escaping, SQL injection prevention through the ORM, and clickjacking protection. However, "secure by default" only works if you do not disable these features. Many vulnerabilities come from developers bypassing Django's protections.

How do I store Django SECRET_KEY safely?

Never hardcode SECRET_KEY in your source code or commit it to version control. Store it as an environment variable on your server. Use packages like django-environ or python-decouple to load it from .env files (which should be in .gitignore). Generate a strong key using django.core.management.utils.get_random_secret_key().

Should I use Django's built-in authentication or a third-party package?

For most applications, Django's built-in authentication system is secure and sufficient. For social authentication (Google, Facebook login), use django-allauth. For API authentication, use Django REST Framework's token or JWT authentication. Avoid building custom authentication from scratch unless you have specific requirements.

How often should I update Django for security?

Monitor Django's security releases and apply them as soon as possible — ideally within a week of release. Subscribe to Django's security mailing list for notifications. Major version updates can be done quarterly, but security patches should be applied immediately. Use pip-audit or safety to check for known vulnerabilities.

What is the most common Django security mistake?

The most common mistake is leaving DEBUG = True in production. This exposes detailed error pages with settings, database queries, file paths, and other sensitive information to anyone who triggers an error. Always use separate settings files for development and production, and verify DEBUG is False before deploying.


Build Secure Django Applications

Security is a skill that separates professional developers from hobbyists. At Swift Academy in Pokhara, our Python Django Full Stack course includes dedicated modules on security best practices, secure deployment, and building production-ready applications that protect user data.

Explore Our Python Django Course in Pokhara and learn to build web applications that are secure from day one.


Related Articles

  1. Python Django Course in Pokhara
  2. Django vs Laravel: Which Framework to Learn
  3. Full Stack Developer Roadmap 2026

Suggested Images

  1. Hero Image: Infographic showing common Django security threats and their protections — Alt: "Django security best practices overview showing common attacks and defenses"
  2. Mid-Article: Code screenshot of production security settings configuration — Alt: "Django production security settings configuration example"
  3. Bottom CTA: Photo of Django development training at Swift Academy Pokhara — Alt: "Django security training at Swift Academy Pokhara Nepal"

Related Posts

Django Security Best Practices: Protect Your Web Application from Common Attacks - Swift Academy