TExcelTAD
Home › Django › Django Security

Django Security

Django has a strong security record because its defaults are safe: you get protection against the most common web attacks without writing any extra code. But protections can be switched off — sometimes by accident. This lesson shows what each defence does, demonstrates it running, and lists the habits that keep it working.

Attack What it is Django's defence
XSS (cross-site scripting) attacker's <script> ends up in your page template auto-escaping
CSRF (cross-site request forgery) another site makes the victim's browser submit your forms CSRF tokens + CsrfViewMiddleware
SQL injection input changes the SQL query ORM uses parameterised queries
Clickjacking your page is framed invisibly by another site X-Frame-Options: DENY header
Host header attacks forged Host poisons links ALLOWED_HOSTS
Password theft leaked database reveals passwords salted, slow password hashing

XSS: auto-escaping

Any {{ variable }} is HTML-escaped before it's inserted, so user input is displayed as text instead of being executed:

python · try it yourself
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
from django.utils.safestring import mark_safe
from django.utils.html import format_html

evil = '<img src=x onerror="alert(document.cookie)">'
t = Template("<p>Comment: {{ comment }}</p>")
print(t.render(Context({"comment": evil})))

# DANGER: marking user input as safe disables the protection
print(t.render(Context({"comment": mark_safe(evil)})))

# Safe way to build HTML in Python: format_html escapes the arguments
print(format_html('<a href="/u/{}">{}</a>', 42, evil))
<p>Comment: &lt;img src=x onerror=&quot;alert(document.cookie)&quot;&gt;</p>
<p>Comment: <img src=x onerror="alert(document.cookie)"></p>
<a href="/u/42">&lt;img src=x onerror=&quot;alert(document.cookie)&quot;&gt;</a>

Rules of thumb:

  • Never call mark_safe() or use |safe / {% autoescape off %} on anything that contains user input.
  • Build HTML in Python with format_html(), which escapes its arguments.
  • Escaping protects HTML text, not every context: don't put user data into <script> blocks or onclick attributes directly — use the json_script filter for passing data to JavaScript.

CSRF: tokens for state-changing requests

A malicious site can't read your pages, but it can make a logged-in victim's browser submit a form to your site — with the victim's cookies attached. Django blocks that by requiring every POST (PUT, PATCH, DELETE) to include a secret CSRF token that only your own pages know. In templates you add it with {% csrf_token %}.

The test client normally skips CSRF checks; Client(enforce_csrf_checks=True) turns them on so we can watch the protection work:

python · try it yourself
import sys, types, re, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
    SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
    MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}],
)
django.setup()
from django.http import HttpResponse
from django.template import engines
from django.urls import path
from django.test import Client

FORM = engines["django"].from_string(
    '<form method="post">{% csrf_token %}<input name="amount"></form>')

def transfer(request):
    if request.method == "POST":
        return HttpResponse(f"Transferred {request.POST['amount']}")
    return HttpResponse(FORM.render({}, request))

urls.urlpatterns = [path("transfer/", transfer)]

attacker = Client(enforce_csrf_checks=True)
r = attacker.post("/transfer/", {"amount": "1000"})        # forged request, no token
print("without token:", r.status_code)

user = Client(enforce_csrf_checks=True)
page = user.get("/transfer/").content.decode()             # sets the csrftoken cookie
token = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', page).group(1)
print("hidden field present:", len(token) == 64)
r = user.post("/transfer/", {"amount": "50", "csrfmiddlewaretoken": token})
print("with token:   ", r.status_code, r.content.decode())
without token: 403
hidden field present: True
with token:    200 Transferred 50

Note: @csrf_exempt switches the protection off for one view. Only use it for endpoints that don't rely on cookies for authentication (e.g. token-authenticated APIs or webhooks verified by signature).

SQL injection

ORM lookups always send values as parameters (see Filter). The risk returns only when you write raw SQL with string formatting. If you need raw SQL, pass parameters separately:

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection

class Account(models.Model):
    username = models.CharField(max_length=30)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Account)
Account.objects.bulk_create([Account(username=u) for u in ["alice", "bob", "carol"]])

user_input = "nobody' OR '1'='1"

# WRONG: string formatting puts the input inside the SQL text
unsafe = Account.objects.raw(f"SELECT * FROM demo_account WHERE username = '{user_input}'")
print("unsafe query matched:", [a.username for a in unsafe])

# RIGHT: params are sent separately and treated as plain data
safe = Account.objects.raw("SELECT * FROM demo_account WHERE username = %s", [user_input])
print("safe query matched:  ", [a.username for a in safe])
print("ORM filter matched:  ", list(Account.objects.filter(username=user_input)))
unsafe query matched: ['alice', 'bob', 'carol']
safe query matched:   []
ORM filter matched:   []

The formatted query returned every account — exactly what an attacker wants.

Security headers

Several middleware add protective HTTP headers. With the default middleware stack you get these on every response:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
    SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
    MIDDLEWARE=["django.middleware.security.SecurityMiddleware",
                "django.middleware.clickjacking.XFrameOptionsMiddleware"],
)
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client

urls.urlpatterns = [path("", lambda request: HttpResponse("hi"))]
r = Client().get("/")
for header in ["X-Frame-Options", "X-Content-Type-Options", "Referrer-Policy", "Cross-Origin-Opener-Policy"]:
    print(f"{header}: {r.headers.get(header)}")
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
Header Protects against
X-Frame-Options: DENY clickjacking (page can't be framed)
X-Content-Type-Options: nosniff browsers guessing a dangerous content type
Referrer-Policy leaking full URLs to other sites
Strict-Transport-Security (with SECURE_HSTS_SECONDS) downgrade to plain HTTP

Security checklist

  • Keep DEBUG = False and SECRET_KEY secret in production; run manage.py check --deploy.
  • Serve the whole site over HTTPS and set the *_SECURE cookie settings.
  • Never trust input: validate with forms, use the ORM or parameterised SQL, avoid |safe on user data.
  • Check permissions in every view that changes or reveals data — hiding a button is not access control.
  • Keep Django and dependencies up to date (pip list --outdated), and subscribe to Django's security announcements.

Test yourself

What does Django's template auto-escaping protect against?

  1. SQL injection
  2. Cross-site scripting (XSS)
  3. CSRF
  4. Clickjacking

What does a POST without a valid CSRF token receive when CsrfViewMiddleware is active?

  1. 200 OK
  2. 302 redirect
  3. 403 Forbidden
  4. 500 error

Which raw SQL call is safe?

  1. raw(f"... WHERE name = '{name}'")
  2. raw("... WHERE name = '%s'" % name)
  3. raw("... WHERE name = %s", [name])
  4. raw("... WHERE name = " + name)