Django templates automatically escape variables to prevent malicious scripts from running in the browser.
Step 2: Compare options with this behavior
Only It automatically escapes variables to prevent malicious code execution. correctly states this automatic escaping feature, while others describe incorrect or unrelated behaviors.
Final Answer:
It automatically escapes variables to prevent malicious code execution. -> Option B
Quick Check:
Default escaping = It automatically escapes variables to prevent malicious code execution. [OK]
5. You want to display user comments that may contain safe HTML tags like <b> and <i>, but prevent scripts. Which approach best prevents XSS while allowing these tags?
hard
A. Sanitize the comment in the backend to allow only safe tags, then use {{ comment|safe }}.
B. Use {{ comment|safe }} directly in the template.
C. Escape the comment with {{ comment|escape }} and then use |safe.
D. Store comments as plain text and never allow any HTML tags.
Solution
Step 1: Understand the need to allow some HTML safely
Allowing safe tags requires cleaning input to remove dangerous scripts but keep allowed tags.
Step 2: Choose the correct method
Sanitizing backend input to whitelist safe tags then marking safe in template is the secure way.
Step 3: Evaluate other options
Using {{ comment|safe }} directly risks XSS by trusting raw input; combining |escape and |safe misuses filters; disallowing all HTML prevents desired formatting.
Final Answer:
Sanitize the comment in the backend to allow only safe tags, then use {{ comment|safe }}. -> Option A
Quick Check:
Backend sanitize + safe filter = Sanitize the comment in the backend to allow only safe tags, then use {{ comment|safe }}. [OK]
Hint: Clean input backend, then mark safe in template [OK]
Common Mistakes:
Trusting raw user input with safe filter
Misusing escape and safe filters together
Disallowing all HTML when some is needed
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.