Django: How to fix the annoying UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)

2 comments

A somewhat tricky error to debug.

Take for example this:

>>> u"%s" % Product.objects.get(pk = 7431).manufacturer 
u'DéLonghi'

Now look at it again.

>>> "%s" % Product.objects.get(pk = 7431).manufacturer
'D\xc3\xa9Longhi'

Did you spot the difference? There's a "u" in front of the string. That "u" tells Python you want it to be a unicode string rather than an ASCII string.

>>> product = Product.objects.get(pk = 7431)

>>> "%s %s" % (product.manufacturer, product.name)

Will throw this exception

Traceback (most recent call last):
  File "<console>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)

Using the unicode string formatter:

>>> product = Product.objects.get(pk = 7431)

>>> u"%s %s" % (product.manufacturer, product.name)
u'D\xe9Longhi PLS130ARAUP'

Phew, that took a while to figure out. Now back to work!

image

2 comments:

  1. This was really helpful and led me down the right path to a fix. Using str() in your __unicode__ method will cause this as well. For instance, you might use an iterator with str() to loop through related objects and coerce to string. Use unicode() instead if you're in a __unicode__ method.

    ReplyDelete

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog