Log in

Django Templating

Django templating

Escaping

HTML Entity Escaping

Since Django 1.0, autoescaping is enabled by default. Any variable not manually escaped or passed through the |safe filter is escaped using the routine below.

Django has |escape and |force_escape filters. Documentation Source

Warning:

Django's HTML escaping will not protect you from Cross-Site Scripting if you do not quote your HTML attributes.

Always quote your HTML attributes!

django.utils.html.escape:

30	def escape(html):
31	    """
32	    Returns the given HTML with ampersands, quotes and angle brackets encoded.
33	    """
34	    return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
35	escape = allow_lazy(escape, unicode)
Javascript Escaping

Django has an |escapejs filter which the documentation indicates is "for use in JavaScript strings."

Warning:

Always quote your HTML attributes, including event handlers!

The escapejs filter in 1.2.1:

66	_base_js_escapes = (
67	    ('\\', r'\u005C'),
68	    ('\'', r'\u0027'),
69	    ('"', r'\u0022'),
70	    ('>', r'\u003E'),
71	    ('<', r'\u003C'),
72	    ('&', r'\u0026'),
73	    ('=', r'\u003D'),
74	    ('-', r'\u002D'),
75	    (';', r'\u003B'),
76	    (u'\u2028', r'\u2028'),
77	    (u'\u2029', r'\u2029')
78	)
79	
80	# Escape every ASCII character with a value less than 32.
81	_js_escapes = (_base_js_escapes +
82	               tuple([('%c' % z, '\\u%04X' % z) for z in range(32)]))
83	
84	def escapejs(value):
85	    """Hex encodes characters for use in JavaScript strings."""
86	    for bad, good in _js_escapes:
87	        value = value.replace(bad, good)
88	    return value
89	escapejs = stringfilter(escapejs)

  • Version: latest
  • Edited by Craig Younkins on 6/23/10 2:47 PM
  • History
  • Edit

An OWASP project created by Craig Younkins

Powered by Moe and Google App Engine