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

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

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