← Back to Chapters

Preventing XSS & SQL Injection in Django

?️ Preventing XSS & SQL Injection in Django

? Quick Overview

Cross-Site Scripting (XSS) and SQL Injection are critical security vulnerabilities. Django provides built-in protections that help developers build secure web applications when used correctly.

? Key Concepts

  • XSS (Cross-Site Scripting)
  • SQL Injection
  • Django Template Auto-Escaping
  • Django ORM Security
  • CSRF Protection

? What is XSS (Cross-Site Scripting)?

XSS occurs when attackers inject malicious scripts into web pages viewed by other users.

1️⃣ Django Template Auto Escaping

? View Code Example
// Django auto-escapes user input in templates

{{ user_input }}

2️⃣ Sanitizing HTML with Bleach

? View Code Example
// Sanitize user HTML safely using bleach
import bleach
cleaned_input = bleach.clean(user_input)

?️ What is SQL Injection?

SQL Injection allows attackers to manipulate database queries through malicious input.

1️⃣ Using Django ORM

? View Code Example
// Django ORM safely handles SQL queries
from myapp.models import MyModel
data = MyModel.objects.filter(field_name=user_input)

2️⃣ Parameterized Queries

? View Code Example
// Parameterized raw SQL query prevents injection
from django.db import connection
with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM myapp_mymodel WHERE field_name = %s",[user_input])

?️ Preventing Other Vulnerabilities

Django includes CSRF protection and supports Content Security Policy (CSP) headers.

? Use Cases

  • Secure form submissions
  • Prevent malicious script execution
  • Protect databases from unauthorized access

? Interactive Defense Simulator

Type a malicious string (e.g. <script>alert(1)</script> or ' OR '1'='1) to see how Django handles it.

✅ Tips & Best Practices

  • Always rely on Django ORM
  • Escape and sanitize user inputs
  • Enable CSRF protection
  • Use CSP headers

? Try It Yourself

  • Test XSS escaping in templates
  • Try SQL injection attempts with ORM
  • Experiment with bleach sanitization