Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: gettext and coercing to unicode

I have following code in my django application.

class Status(object):

    def __init__(self, id, desc):
        self.id = id
        self.desc = desc

    def __unicode__(self):
        return self.desc

STATUS = Status(0, _(u"Some text"))

When I try to display some status (or even coerce it to unicode), I get:

TypeError: coercing to Unicode: need string or buffer, __proxy__ found

Could anyone explain me, what I am doing wrong?

like image 444
gruszczy Avatar asked Jan 25 '10 15:01

gruszczy


2 Answers

The _() function from Django can return a django.utils.functional.__proxy__ object, which is itself not unicode (see http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings). Python does not call unicode() recursively, so it's an error for your Status object to return the __proxy__ object directly. You need to make the __unicode__ method return unicode(self.desc).

Note that this is specific to Django; Python's own gettext doesn't return these proxy objects.

like image 67
Thomas Wouters Avatar answered Nov 12 '22 18:11

Thomas Wouters


I assume that @thomas-wounters solved your issue, but for others who might have a similar issue - please check if you are not using ugettext_lazy:

from django.utils.translation import ugettext_lazy as _

in that case, you must cast output to str/unicode:

unicode(_('translate me'))
like image 1
TenaciousRaptor Avatar answered Nov 12 '22 16:11

TenaciousRaptor