0

deal_instance_name我似乎在 Deal 模型中遇到了 unicode 问题。

它说:

coercing to Unicode: need string or buffer, __proxy__ found

异常发生在这一行:

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

如果我删除该行,smart_unicode(self.deal_type.deal_name)但为什么?

那时在 Django 1.1 中,有人在Stackoverflow上遇到了同样的问题,我尝试unicode()了新的和新的smart_unicode(),没有任何快乐。

请问我会错过什么?

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')

交易类型:

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')
4

1 回答 1

2

实际上,该smart_unicode部分与您的问题无关:

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

会提出完全相同的问题。

这基本上是因为ugettext_lazy(u'efg')不会返回unicode字符串,而是 a __proxy__,当你这样做时会引发错误u'abc' + ugettext_lazy(u'eg')

你会得到完全相同的问题:u'a' + 1

您可以使用以下方法解决此问题:

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

或者,您可以ugettext_lazy(u'efg')使用.unicodeunicode(ugettext_lazy(u'efg'))

于 2012-09-11T21:51:51.457 回答