From 4a3db287f1c86f7e66408432b381190bc9d0557d Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick Date: Mon, 2 Apr 2007 10:53:05 +0000 Subject: [PATCH] Fixed #3600 -- Made smart_unicode respect deferred evaluation in the case of strings translated with gettext_lazy and friends. git-svn-id: http://code.djangoproject.com/svn/django/trunk@4904 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/newforms/util.py | 11 +++++++++++ tests/regressiontests/forms/regressions.py | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/django/newforms/util.py b/django/newforms/util.py index 51a8efdde2..f98027c2e3 100644 --- a/django/newforms/util.py +++ b/django/newforms/util.py @@ -1,11 +1,20 @@ from django.conf import settings from django.utils.html import escape +from django.utils.functional import Promise, lazy # Converts a dictionary to a single string with key="value", XML-style with # a leading space. Assumes keys do not need to be XML-escaped. flatatt = lambda attrs: u''.join([u' %s="%s"' % (k, escape(v)) for k, v in attrs.items()]) def smart_unicode(s): + if isinstance(s, Promise): + # The input is something from gettext_lazy or similar. We don't want to + # translate it until render time, so defer the conversion. + return smart_unicode_lazy(s) + else: + return smart_unicode_immediate(s) + +def smart_unicode_immediate(s): if not isinstance(s, basestring): if hasattr(s, '__unicode__'): s = unicode(s) @@ -15,6 +24,8 @@ def smart_unicode(s): s = unicode(s, settings.DEFAULT_CHARSET) return s +smart_unicode_lazy = lazy(smart_unicode_immediate, unicode) + class StrAndUnicode(object): """ A class whose __str__ returns its __unicode__ as a bytestring diff --git a/tests/regressiontests/forms/regressions.py b/tests/regressiontests/forms/regressions.py index dc5232a8f0..02b38ec58d 100644 --- a/tests/regressiontests/forms/regressions.py +++ b/tests/regressiontests/forms/regressions.py @@ -10,4 +10,20 @@ It should be possible to re-use attribute dictionaries (#3810) ... f2 = CharField(widget=TextInput(attrs=extra_attrs)) >>> TestForm(auto_id=False).as_p() u'

F1:

\n

F2:

' + +####################### +# Tests for form i18n # +####################### +There were some problems with form translations in #3600 + +>>> from django.utils.translation import gettext_lazy, activate, deactivate +>>> class SomeForm(Form): +... username = CharField(max_length=10, label=gettext_lazy('Username')) +>>> f = SomeForm() +>>> print f.as_p() +

+>>> activate('de') +>>> print f.as_p() +

+>>> deactivate() """