summaryrefslogtreecommitdiff
path: root/django/utils/encoding.py
diff options
context:
space:
mode:
authorMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2007-04-04 06:34:19 +0000
committerMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2007-04-04 06:34:19 +0000
commit1bddac37b69152d919a3af29f2844ae3e34c7237 (patch)
tree1d6663957982521930b1ff5d85e12d5b7d7e9917 /django/utils/encoding.py
parentf791a598a8e207a6f362ea75b9474f7739b518c7 (diff)
downloaddjango-1bddac37b69152d919a3af29f2844ae3e34c7237.tar.gz
Moved smart_unicode and StrAndUnicode to django.utils.encoding. They are useful
outside of newforms. This is backwards compatible as far as smart_unicode goes (since newforms.util still imports it). All imports of smart_unicode and StrAndUnicode have also been updated. git-svn-id: http://code.djangoproject.com/svn/django/trunk@4918 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/utils/encoding.py')
-rw-r--r--django/utils/encoding.py28
1 files changed, 28 insertions, 0 deletions
diff --git a/django/utils/encoding.py b/django/utils/encoding.py
new file mode 100644
index 0000000000..bf59f44e31
--- /dev/null
+++ b/django/utils/encoding.py
@@ -0,0 +1,28 @@
+from django.conf import settings
+from django.utils.functional import Promise
+
+def smart_unicode(s):
+ if isinstance(s, Promise):
+ # The input is the result of a gettext_lazy() call, or similar. It will
+ # already be encoded in DEFAULT_CHARSET on evaluation and we don't want
+ # to evaluate it until render time.
+ return s
+ if not isinstance(s, basestring,):
+ if hasattr(s, '__unicode__'):
+ s = unicode(s)
+ else:
+ s = unicode(str(s), settings.DEFAULT_CHARSET)
+ elif not isinstance(s, unicode):
+ s = unicode(s, settings.DEFAULT_CHARSET)
+ return s
+
+class StrAndUnicode(object):
+ """
+ A class whose __str__ returns its __unicode__ as a bytestring
+ according to settings.DEFAULT_CHARSET.
+
+ Useful as a mix-in.
+ """
+ def __str__(self):
+ return self.__unicode__().encode(settings.DEFAULT_CHARSET)
+