Preventing CSRF, XSS & SQL Injection
CSRF, XSS, and SQL Injection are the three most common web attacks. Django protects against all three by default - but you must understand how they work to avoid accidentally disabling protections.
20 min•By Priygop Team•Updated 2026
The Big Three Attacks
- CSRF - Forged form submissions from malicious sites
- XSS - Injecting JavaScript into pages via user input
- SQL Injection - Injecting SQL commands via user input
- Django prevents CSRF with tokens ({% csrf_token %})
- Django prevents XSS with auto-escaping in templates
- Django prevents SQL Injection by parameterizing queries in the ORM
- NEVER disable these protections without understanding the risk
Attack Prevention
Attack Prevention
# 1. SQL INJECTION
# BAD - vulnerable to SQL injection:
# query = f"SELECT * FROM blog_post WHERE title = '{user_input}'"
# Post.objects.raw(query)
# If user_input = "'; DROP TABLE blog_post; --"
# The entire table gets deleted!
# GOOD - Django ORM parameterizes queries:
# Post.objects.filter(title=user_input)
# Django generates: SELECT * FROM blog_post WHERE title = %s
# The user input is treated as DATA, not SQL code.
# 2. XSS (Cross-Site Scripting)
# User submits: <script>alert('hacked')</script>
# SAFE (default) - auto-escaped:
# {{ user_comment }}
# Renders: <script>alert('hacked')</script>
# DANGEROUS - escaping disabled:
# {{ user_comment|safe }} <- NEVER do this with user input!
# 3. CSRF (Cross-Site Request Forgery)
# Always include in forms:
# <form method="post">
# {% csrf_token %}
# ...
# </form>
# For AJAX:
# Include X-CSRFToken header from csrftoken cookie?? Tip
Tip
Django's ORM uses parameterized queries automatically. Never use string formatting for SQL - always use .filter() or raw() with params.
Diagram
Loading diagram…
QuerySets are LAZY - no DB hit until evaluated.
?? Common Mistake
Warning
Using raw SQL with string formatting: cursor.execute(f'SELECT * WHERE id={id}'). This enables SQL injection attacks.
?? Practice Task
Note
(1) Test Django's CSRF protection. (2) Verify SQL injection protection with .filter(). (3) Test XSS auto-escaping.
Quick Quiz
Key Takeaways
- CSRF, XSS, and SQL Injection are the three most common web attacks.
- CSRF - Forged form submissions from malicious sites
- XSS - Injecting JavaScript into pages via user input
- SQL Injection - Injecting SQL commands via user input