Learn / Frameworks / Django / Security Defaults

Django · Lesson 14 of 15

Security Defaults

CSRF, XSS, SQL injection, HTTPS and the deployment checklist.

  • Advanced
  • 15 min read
  • 3 objectives

Before this lessonLesson 13: Sessions, Messages and Email

What you will learn

  • Explain CSRF
  • Lock down HTTPS
  • Run the deployment checks

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Django's defaults already block the usual attacks. Production is about leaving those defaults on and turning the HTTPS settings up.

What you get for free

  • CSRF: every POST form needs {% csrf_token %}. APIs that use cookies need the CSRF header too.
  • XSS: templates auto-escape. Only use |safe on trusted HTML.
  • SQL injection: the ORM parameterises queries. Never interpolate user input into raw().
  • Clickjacking: X-Frame-Options middleware.

HTTPS and cookies

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

The checklist

python manage.py check --deploy

Fix every warning before you ship. Keep SECRET_KEY and database passwords in the environment, not in git. DEBUG = False in production or you leak stack traces.

Up next · Lesson 15Deployment with GunicornProduction settings, gunicorn, Nginx, collectstatic and migrations on release.