Bird
0
0

Identify the error in this Django ORM code that tries to prevent SQL injection:

medium📝 Debug Q14 of 15
Django - Security Best Practices
Identify the error in this Django ORM code that tries to prevent SQL injection:
query = "SELECT * FROM users WHERE username = '%s'" % user_input
users = User.objects.raw(query)
AThe raw() method automatically escapes inputs, so no error.
BUsing raw SQL with string formatting allows SQL injection.
CThe filter() method should be used instead of raw().
DThe query string is missing parameter placeholders.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze string formatting with user input

    Using % formatting inserts user_input directly, risking SQL injection.
  2. Step 2: Understand raw() method behavior

    raw() executes raw SQL without escaping, so injection risk remains.
  3. Final Answer:

    Using raw SQL with string formatting allows SQL injection. -> Option B
  4. Quick Check:

    String formatting + raw() = injection risk = A [OK]
Quick Trick: Never build raw SQL with string formatting; use ORM methods [OK]
Common Mistakes:
MISTAKES
  • Assuming raw() escapes inputs
  • Using raw SQL instead of filter()
  • Ignoring injection risk in string formatting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes