0
0
Djangoframework~5 mins

XSS prevention in templates in Django

Choose your learning style9 modes available
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.

When showing user input on a webpage, like comments or names.
When displaying data from external sources that might be unsafe.
When building forms that show error messages or feedback.
When rendering any dynamic content that users can change.
When you want to keep your website secure and trustworthy.
Syntax
Django
{% autoescape on %}
{{ variable }}
{% endautoescape %}
Django templates escape variables by default to prevent XSS.
Use the safe filter only when you trust the content.
Examples
This shows user input safely by escaping HTML special characters.
Django
{{ user_input }}
This tells Django not to escape the content. Use only if you trust the input.
Django
{{ user_input|safe }}
Disables escaping inside the block. Use carefully to avoid XSS risks.
Django
{% autoescape off %}
{{ raw_html }}
{% endautoescape %}
Sample Program

This template safely shows a user comment. If the comment contains HTML tags, they will be shown as text, not as code.

Django
{# 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>
OutputSuccess
Important Notes

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.

Summary

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.