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 20:01:41 -0400
commit44a05a8a912596c44f37f050dcde85b45827b3b6 (patch)
tree237d32eff118beb88ebbb0c29eaff456978bdbfa /django/utils/html.py
parent6a2f46f2381269187195a0f9165a893f54dc01a3 (diff)
[1.8.x] Fixed #24469 -- Refined escaping of Django's form elements in non-Django templates.
Backport of 1f2abf784a9fe550959de242d91963b2ad6f7e9c from master
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 4197dc9e23..eabbb16467 100644
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -368,3 +368,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