How to Fix SQL Injection in Django
Learn how to prevent and fix SQL Injection vulnerabilities in Django applications. Step-by-step guide with code examples, security checklists, and best practices.
What Is SQL Injection?
SQL Injection is a code injection technique that exploits security vulnerabilities in an application's database layer. It occurs when user-supplied data is included in SQL queries without proper sanitization, allowing an attacker to manipulate the query's logic. An attacker can craft input that changes the intended SQL command, gaining unauthorized access to data.
The attack works by inserting (or "injecting") SQL fragments into input fields, URL parameters, cookies, or HTTP headers that are then incorporated into database queries. For example, a login form vulnerable to SQL injection might allow an attacker to bypass authentication by entering `' OR '1'='1` as a password. More sophisticated attacks can use UNION-based injection to extract data from other tables, blind injection to infer data one bit at a time, or stacked queries to execute arbitrary SQL commands.
While ORMs and query builders have reduced the prevalence of SQL injection, it remains common in applications that use raw queries, dynamic query construction, or improperly configured ORMs. Stored procedures are not immune either if they construct dynamic SQL internally.
Why It Matters
SQL Injection consistently ranks among the most dangerous web vulnerabilities because of its severe impact. A successful attack can lead to complete database compromise, allowing attackers to read all data including credentials, personal information, and financial records. Attackers can modify or delete data, causing data integrity issues and potential business disruption. In some database configurations, SQL injection can be escalated to operating system command execution, leading to full server compromise. The 2017 Equifax breach, which exposed 147 million records, was caused by a related injection vulnerability. For applications subject to regulations like GDPR or HIPAA, a SQL injection breach can result in millions of dollars in fines.
How to Fix It in Django
The most effective defense against SQL injection is using parameterized queries (also called prepared statements) for all database interactions. Never concatenate user input directly into SQL strings. Use your ORM's built-in query methods rather than raw SQL wherever possible. If raw queries are necessary, always use parameterized placeholders. Implement input validation using strict allowlists for expected data types and formats. Apply the principle of least privilege to database accounts -- the application should connect with minimal necessary permissions. Use a Web Application Firewall (WAF) as an additional layer. Regularly audit your codebase for raw query construction patterns.
Django-Specific Advice
- Django's template engine auto-escapes HTML by default. Never use the `|safe` filter or `mark_safe()` with unsanitized user input.
- Use Django's ORM for all database queries. When raw SQL is needed, always use parameterized queries: `cursor.execute('SELECT ... WHERE id = %s', [user_id])`.
- Keep Django's CSRF middleware enabled. Use `{% csrf_token %}` in all forms and configure CSRF for AJAX requests.
- Set `DEBUG = False` in production. Debug mode exposes detailed error pages with sensitive information.
Code Examples
# DANGEROUS -- SQL injection via f-string
def get_user(request, user_id):
with connection.cursor() as cursor:
cursor.execute(
f"SELECT * FROM users WHERE id = '{user_id}'"
)
return JsonResponse(cursor.fetchone())# Option 1: Use Django ORM (always safe)
def get_user(request, user_id):
user = User.objects.get(id=user_id)
return JsonResponse(model_to_dict(user))
# Option 2: Parameterized raw SQL
def get_user(request, user_id):
with connection.cursor() as cursor:
cursor.execute(
"SELECT * FROM users WHERE id = %s",
[user_id]
)
return JsonResponse(cursor.fetchone())Django Security Checklist for SQL Injection
Django Security Best Practices
Django's template engine auto-escapes HTML by default. Never use the `|safe` filter or `mark_safe()` with unsanitized user input.
Use Django's ORM for all database queries. When raw SQL is needed, always use parameterized queries: `cursor.execute('SELECT ... WHERE id = %s', [user_id])`.
Keep Django's CSRF middleware enabled. Use `{% csrf_token %}` in all forms and configure CSRF for AJAX requests.
Set `DEBUG = False` in production. Debug mode exposes detailed error pages with sensitive information.
Use Django's built-in password hashing (PBKDF2 by default) and never implement custom password storage.
Configure `SECURE_SSL_REDIRECT`, `SECURE_HSTS_SECONDS`, `SESSION_COOKIE_SECURE`, and `CSRF_COOKIE_SECURE` in production settings.
Use `django-ratelimit` or Django REST Framework's throttling for rate limiting on authentication and API endpoints.
Keep `SECRET_KEY` secret and unique per environment. Rotate it if it is ever exposed.
Scan Your Django App with SafeVibe
Stop guessing if your Django app is vulnerable to SQL Injection. Run an automated penetration test in minutes and get actionable results.
Start Free Scan