From 1bddac37b69152d919a3af29f2844ae3e34c7237 Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick Date: Wed, 4 Apr 2007 06:34:19 +0000 Subject: 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 --- django/utils/encoding.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 django/utils/encoding.py (limited to 'django/utils/encoding.py') 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) + -- cgit v1.2.1