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.
XSS occurs when attackers inject malicious scripts into web pages viewed by other users.
// Django auto-escapes user input in templates
{{ user_input }}
// Sanitize user HTML safely using bleach
import bleach
cleaned_input = bleach.clean(user_input)
SQL Injection allows attackers to manipulate database queries through malicious input.
// Django ORM safely handles SQL queries
from myapp.models import MyModel
data = MyModel.objects.filter(field_name=user_input)
// 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])
Django includes CSRF protection and supports Content Security Policy (CSP) headers.
Type a malicious string (e.g. <script>alert(1)</script> or ' OR '1'='1) to see how Django handles it.