0
0
DjangoDebug / FixBeginner · 4 min read

How to Prevent SQL Injection in Django Securely

To prevent SQL injection in Django, always use Django's ORM methods or parameterized queries with raw(). Avoid building SQL strings by concatenating user input directly.
🔍

Why This Happens

SQL injection happens when user input is directly added to SQL queries without proper checks. This lets attackers run harmful commands on your database.

python
from django.db import connection

def get_user_data(username):
    query = f"SELECT * FROM auth_user WHERE username = '{username}'"
    with connection.cursor() as cursor:
        cursor.execute(query)
        return cursor.fetchall()
Output
If username is "admin' OR '1'='1", this query returns all users, exposing data.
🔧

The Fix

Use Django's ORM to build queries safely or use parameterized queries with cursor.execute() to avoid injecting user input directly into SQL strings.

python
from django.contrib.auth.models import User

def get_user_data(username):
    # Safe ORM query
    return User.objects.filter(username=username)

# Or using parameterized raw SQL
from django.db import connection

def get_user_data_raw(username):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM auth_user WHERE username = %s", [username])
        return cursor.fetchall()
Output
Returns only the user with the exact username, preventing injection.
🛡️

Prevention

Always use Django ORM for database queries as it automatically escapes inputs. If raw SQL is needed, use parameterized queries with placeholders. Never concatenate user input into SQL strings. Enable Django's security middleware and keep dependencies updated.

  • Use filter(), get(), and other ORM methods.
  • Use parameterized queries with cursor.execute(sql, params).
  • Validate and sanitize user inputs where possible.
  • Keep Django and database drivers updated.
⚠️

Related Errors

Other common errors include:

  • Improper escaping: Using string interpolation instead of parameters causes injection.
  • Using raw SQL without parameters: Leads to injection risks.
  • Not validating inputs: Can cause unexpected behavior or injection.

Key Takeaways

Always use Django ORM methods to build queries safely.
Never concatenate user input directly into SQL strings.
Use parameterized queries with placeholders when using raw SQL.
Validate and sanitize user inputs to reduce risks.
Keep Django and dependencies updated for security patches.