Houman
Houman

Reputation: 66320

Unicode issue in Django

I seem to have a unicode problem with the deal_instance_name in the Deal model.

It says:

coercing to Unicode: need string or buffer, __proxy__ found

The exception happens on this line:

return smart_unicode(self.deal_type.deal_name) + _(u' - Set No.')  + str(self.set)

The line works if I remove smart_unicode(self.deal_type.deal_name) but why?

Back then in Django 1.1 someone had the same problem on Stackoverflow I have tried both the unicode() as well as the new smart_unicode() without any joy.

What could I be missing please?

class Deal(models.Model):
    def __init__(self, *args, **kwargs):
        super(Deal, self).__init__(*args, **kwargs)      
        self.deal_instance_name = self.__unicode__()      

    deal_type           = models.ForeignKey(DealType)
    deal_instance_name  = models.CharField(_(u'Deal Name'), max_length=100)    
    set                 = models.IntegerField(_(u'Set Number'))

    def __unicode__(self):
        return smart_unicode(self.deal_type.deal_name) + _(u' - Set No.')  + smart_unicode(self.set)

    class Meta:
        verbose_name = _(u'Deal')
        verbose_name_plural = _(u'Deals')

Dealtype:

class DealType(models.Model):    
    deal_name           = models.CharField(_(u'Deal Name'), max_length=40)
    deal_description    = models.TextField(_(u'Deal Description'),     blank=True)

    def __unicode__(self):
        return smart_unicode(self.deal_name) 

    class Meta:
        verbose_name = _(u'Deal Type')
        verbose_name_plural = _(u'Deal Types')

Upvotes: 0

Views: 975

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55199

Actually, the smart_unicode part has nothing to do with your issue:

from django.utils.translation import ugettext_lazy
stuff = u'abc' + ugettext_lazy(u'efg')

Would raise the exact same issue.

That's basically because ugettext_lazy(u'efg') will not return an unicode string, but a __proxy__, which will raise an error when you do u'abc' + ugettext_lazy(u'eg').

You would get the exact same issue with: u'a' + 1.

You can solve this issue using:

from django.utils.translation import ugettext_lazy
stuff = u'abc {0}'.format(ugettext_lazy(u'efg'))

Alternatively, you could force ugettext_lazy(u'efg') into an unicode object using unicode(ugettext_lazy(u'efg')).

Upvotes: 2

Related Questions