Introduction
XSS prevention stops bad code from running in your web pages. It keeps users safe from hackers who try to steal information or cause trouble.
Jump into concepts and practice - no test required
XSS prevention stops bad code from running in your web pages. It keeps users safe from hackers who try to steal information or cause trouble.
{% autoescape on %}
{{ variable }}
{% endautoescape %}safe filter only when you trust the content.{{ user_input }}{{ user_input|safe }}{% autoescape off %}
{{ raw_html }}
{% endautoescape %}This template safely shows a user comment. If the comment contains HTML tags, they will be shown as text, not as code.
{# template.html #}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>XSS Prevention Demo</title>
</head>
<body>
<h1>User Comment</h1>
<p>{{ comment }}</p>
</body>
</html>Always trust Django's default escaping unless you have a strong reason not to.
Never use the safe filter on user input without cleaning it first.
Test your templates by trying to insert HTML or script tags to see if they get escaped.
Django templates escape variables by default to protect against XSS.
Use the safe filter only for trusted content.
Always test your app to ensure user input is shown safely.
safe filter tells Django not to escape the variable, rendering HTML as-is.escape escapes content, strip and clean are not standard Django filters for safety.{{ user_input }}<script>alert('XSS')</script>, what will be rendered in the browser?{{ comment|safe }}safe on user input disables escaping, allowing scripts to run if input is malicious.safe to untrusted input is unsafe and causes XSS vulnerabilities.safe filter is used on untrusted user input. [OK]<b> and <i>, but prevent scripts. Which approach best prevents XSS while allowing these tags?{{ comment|safe }} directly risks XSS by trusting raw input; combining |escape and |safe misuses filters; disallowing all HTML prevents desired formatting.{{ comment|safe }}. [OK]