Full answer
SQL injection happens when user input becomes part of the SQL text. If a search box value x' OR '1'='1 is pasted into WHERE name = '...', the attacker changes the query.
Django's protection: QuerySets compile to SQL with placeholders, and the driver sends values separately. The same applies to raw SQL when you pass parameters:
cursor.execute("SELECT ... WHERE name = %s", [name]) # safe
Student.objects.raw("SELECT * FROM s WHERE name = %s", [name]) # safe
cursor.execute(f"SELECT ... WHERE name = '{name}'") # vulnerableEasy ways to break it:
- f-strings,
%or.format()in SQL strings, including insideraw(),RawSQL()andextra(). - Quoting the placeholder yourself:
'%s'(wrong; the driver adds quotes). - Identifiers such as column names or ORDER BY fields cannot be parameterised. Map user input to an allow-list:
order = {"name": "name", "marks": "-marks"}.get(param, "name").
XSS (cross-site scripting) happens when user input becomes part of the page's HTML or JavaScript and runs in other users' browsers.
Django's protection: templates escape < > & ' " by default.
Ways to break it:
{{ comment|safe }},{% autoescape off %}ormark_safe(user_text).- Building HTML in Python with f-strings. Use
format_html("<b>{}</b>", name), which escapes arguments. - Putting data inside
<script>. HTML escaping is not JavaScript escaping. Use{{ data|json_script:"data-id" }}and read it withJSON.parse. href="{{ url }}"with ajavascript:URL. Validate URL schemes.- Rich text from users needs an HTML sanitiser (for example
nh3), not|safe.
Add a Content Security Policy as defence in depth, and keep session cookies HttpOnly so a script cannot read them.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import connection, models
from django.template import Context, Engine
from django.utils.html import format_html
class Student(models.Model):
name = models.CharField(max_length=40)
fee_due = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Student)
Student.objects.create(name="Alok", fee_due=0)
Student.objects.create(name="Bina", fee_due=4500)
attack = "nobody' OR '1'='1"
table = Student._meta.db_table
with connection.cursor() as cur:
cur.execute(f"SELECT name FROM {table} WHERE name = '{attack}'") # vulnerable
print("f-string SQL returned:", cur.fetchall())
cur.execute(f"SELECT name FROM {table} WHERE name = %s", [attack]) # parameterised
print("parameterised SQL returned:", cur.fetchall())
print("ORM returned:", list(Student.objects.filter(name=attack)))
ALLOWED_ORDER = {"name": "name", "fee": "-fee_due"}
user_sort = "fee_due; DROP TABLE x"
print("ordering used:", ALLOWED_ORDER.get(user_sort, "name"))
comment = '<img src=x onerror="alert(1)">'
engine = Engine()
print(engine.from_string("{{ c }}").render(Context({"c": comment})))
print(engine.from_string("{{ c|safe }}").render(Context({"c": comment})), "<- unsafe")
print(format_html("<b>{}</b>", comment))
print(engine.from_string('{{ data|json_script:"marks" }}').render(Context({"data": {"note": "</script><b>"}})))
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The vulnerable query is shown on purpose to demonstrate the attack against a throwaway in-memory database. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): f-string SQL returned: [('Alok',), ('Bina',)] parameterised SQL returned: [] ORM returned: [] ordering used: name <img src=x onerror="alert(1)"> <img src=x onerror="alert(1)"> <- unsafe <b><img src=x onerror="alert(1)"></b> <script id="marks" type="application/json">{"note": "\u003C/script\u003E\u003Cb\u003E"}</script>
Key points
- ORM and parameterised cursor.execute keep values out of SQL text
- f-strings in raw SQL are the classic injection bug
- Use allow-lists for column names and ORDER BY
- Templates auto-escape; |safe and mark_safe on user data cause XSS
- Use format_html and json_script; sanitise rich text
Common mistakes
- Formatting user input into raw SQL strings
- Wrapping the %s placeholder in quotes
- Passing user-chosen column names straight into order_by() or raw SQL
- Using |safe or mark_safe on content that came from users
- HTML-escaping data and then dropping it inside a script block
Follow-ups
- How would you safely allow users to post formatted comments?
- Why can a column name not be passed as a query parameter?
- What does a Content Security Policy add on top of escaping?
Tips
- Show the vulnerable and safe versions side by side
- Name the ways developers bypass protection, not only the defaults
- Mention json_script for data inside JavaScript