Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 5 of 10 · Django Templates
Interview question

How does Django's automatic HTML escaping work, and how do you disable it safely? Django का automatic HTML escaping कैसे काम करता है, और इसे safely कैसे disable करें?

Answer

Django automatically escapes special HTML characters in template variables to prevent Cross-Site Scripting (XSS) attacks, converting characters like <, >, and & into their safe HTML entity equivalents.

# If a book title contains user-submitted HTML/script content:
# book.title = '<script>alert("XSS")</script>'

{{ book.title }}
<!-- Rendered as literal text, NOT executed:
     <script>alert("XSS")</script> -->

# Disabling escaping for a SPECIFIC trusted value with the safe filter
{{ trusted_html_content|safe }}
<!-- Only use this for content YOU control or have sanitized -->

# Disabling escaping for an entire block
{% autoescape off %}
    {{ trusted_content }}
{% endautoescape %}

# Marking a string as safe in Python code (use with extreme caution)
from django.utils.safestring import mark_safe

def render_bold(text):
    return mark_safe(f'<strong>{text}</strong>')
# DANGEROUS if 'text' contains unsanitized user input - only mark_safe()
# content that is fully controlled or has been properly sanitized

# format_html() - safer way to build HTML with dynamic values,
# automatically escapes the ARGUMENTS while keeping the template safe
from django.utils.html import format_html

def render_book_link(book):
    return format_html('<a href="{}">{}</a>', book.get_absolute_url(), book.title)
# book.title is automatically escaped even though the surrounding HTML isn't

# NEVER do this - defeats escaping entirely and is a classic XSS vulnerability:
# return mark_safe(f'<a href="{url}">{user_provided_title}</a>')

Django template variables में special HTML characters को automatically escape करता है XSS attacks रोकने के लिए, <, >, & जैसे characters को safe HTML entities में बदलता है।

# book.title = '<script>alert("XSS")</script>'

{{ book.title }}
<!-- literal text की तरह render होता है, execute नहीं होता:
     <script>alert("XSS")</script> -->

# safe filter से specific trusted value के लिए escaping disable करना
{{ trusted_html_content|safe }}
<!-- सिर्फ ऐसे content के लिए जो आपने control/sanitize किया हो -->

# पूरे block के लिए escaping disable करना
{% autoescape off %}
    {{ trusted_content }}
{% endautoescape %}

# Python code में string को safe mark करना (बहुत सावधानी से)
from django.utils.safestring import mark_safe

def render_bold(text):
    return mark_safe(f'<strong>{text}</strong>')
# खतरनाक अगर 'text' unsanitized user input रखता हो

# format_html() - dynamic values के साथ HTML बनाने का सुरक्षित तरीका
from django.utils.html import format_html

def render_book_link(book):
    return format_html('<a href="{}">{}</a>', book.get_absolute_url(), book.title)
# book.title automatically escape होता है

Was this answer clear?