What is Django security best practices?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
Django has built-in security features and best practices for production: 1. HTTPS everywhere: SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 31536000 SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True. 2. CSRF protection: CsrfViewMiddleware — always enabled. Use {% csrf_token %} in all POST forms. For AJAX: include CSRF token in headers. Exempt specific views: @csrf_exempt (use rarely). 3. XSS prevention: Django templates auto-escape HTML by default. Use |safe filter ONLY for trusted content. 4. SQL injection: Django ORM parameterizes queries — never use string formatting in queries: bad: query = f"SELECT * FROM users WHERE id = {user_id}"; good: User.objects.get(id=user_id). If using raw SQL: User.objects.raw("SELECT * FROM users WHERE id = %s", [user_id]). 5. Secret key: keep SECRET_KEY in environment variables, never in code. Rotate if exposed. 6. DEBUG = False in production: DEBUG exposes stack traces. 7. ALLOWED_HOSTS: prevents HTTP Host header attacks. 8. User input: validate all input — use forms with validators, serializers. 9. File uploads: validate file types/sizes. Store outside web root. Use whitelisted extensions. 10. Dependencies: keep Django and packages updated. Use pip-audit or Snyk. 11. Rate limiting: throttle authentication endpoints. Use fail2ban for brute force. 12. Clickjacking: X_FRAME_OPTIONS = "DENY". 13. Content Security Policy: use django-csp.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Django answers easy to follow.