Class Order: __unicode__ doesn't return a unicode string

Issue #1460 resolved
MechanTOurS
created an issue

Current implementation:

    def __unicode__(self):
        return "Order #%s: %s" % (self.id, self.contact.full_name)

should be:

    def __unicode__(self):
        return u"Order #%s: %s" % (self.id, self.contact.full_name)

Comments (6)

  1. Hynek Cernoch

    It is not necessary because it really returns unicode. Example '%s' % Contact(first_name='a', last_name='b').full_name returns u'a b' If not, than you did probable incorrectly customized the property full_name, but the property full_name should return unicode, not bytestring.

  2. Hynek Cernoch

    Django 1.4 also uses also both return 'some string %s' % some_model_field or similarly with u'...' prefix with a frequency around half to half. In Django 1.5 is the u prefix never used.

  3. MechanTOurS reporter

    Thank you for your analysis,

    I tested again, and __unicode__ correctly returns unicode strings.

    I have some minor traceback in my logs of the form :

    Traceback (most recent call last):
      File "/.../Python-2.7.3/lib/python2.7/logging/__init__.py", line 869, in emit
        stream.write(fs % msg.encode("UTF-8"))
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 67: ordinal not in range(128)
    Logged from file models.py, line 1036
    

    They come from logging calls like:

        def order_success(self):
            """Run each item's order_success method."""
            log.info("Order success: %s", self)
            ...
    

    Which must be calling the __str__ method.

    I have to rewrite them this way to avoid the tracebacks:

    log.info(u"Order success: %s", self) (and it correctly calls the __unicode__ implementation)

  4. Hynek Cernoch

    Yes, logging can correctly treat an objcet converted explicitely to both utf-8 byte string or to unicode but can not guess what to expect finally from self (shop.models.Order).
    Other possible solution is:

    log.info("Order success: %s" % self)
    
  5. Log in to comment