summaryrefslogtreecommitdiff
path: root/django/utils/html.py
diff options
context:
space:
mode:
authorMoritz Sichert <moritz.sichert@googlemail.com>2015-03-18 21:42:59 +0100
committerTim Graham <timograham@gmail.com>2015-03-27 19:46:20 -0400
commit1f2abf784a9fe550959de242d91963b2ad6f7e9c (patch)
treebf56ca4f56279281a24793197fc6bed88781f727 /django/utils/html.py
parentdc5b01ad05e50ccde688c73c2ed3334a956076b0 (diff)
Fixed #24469 -- Refined escaping of Django's form elements in non-Django templates.
Diffstat (limited to 'django/utils/html.py')
-rw-r--r--django/utils/html.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/django/utils/html.py b/django/utils/html.py
index 1cf131b8a0..cafc3ab6e1 100644
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -360,3 +360,34 @@ def avoid_wrapping(value):
spaces where there previously were normal spaces.
"""
return value.replace(" ", "\xa0")
+
+
+def html_safe(klass):
+ """
+ A decorator that defines the __html__ method. This helps non-Django
+ templates to detect classes whose __str__ methods return SafeText.
+ """
+ if '__html__' in klass.__dict__:
+ raise ValueError(
+ "can't apply @html_safe to %s because it defines "
+ "__html__()." % klass.__name__
+ )
+ if six.PY2:
+ if '__unicode__' not in klass.__dict__:
+ raise ValueError(
+ "can't apply @html_safe to %s because it doesn't "
+ "define __unicode__()." % klass.__name__
+ )
+ klass_unicode = klass.__unicode__
+ klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))
+ klass.__html__ = lambda self: unicode(self)
+ else:
+ if '__str__' not in klass.__dict__:
+ raise ValueError(
+ "can't apply @html_safe to %s because it doesn't "
+ "define __str__()." % klass.__name__
+ )
+ klass_str = klass.__str__
+ klass.__str__ = lambda self: mark_safe(klass_str(self))
+ klass.__html__ = lambda self: str(self)
+ return klass