Django admin UnicodeEncodeError

By | June 19, 2013

Don’t we all get confused by unicode encoding sometimes? Especially you wouldn’t expect this kind of error to happen in django admin. The problem is actually not in the admin section, the culprit is __unicode__ method in your model.

when you have a unicode function like this:

def __unicode__(self):
  return "{0}".format(self.field_one)

It is actually returning a ASCII string(which means, it will try to convert field_one to ASCII), if the field_one contains characters outside of ASCII, you will get the problem as above.

Now consider this unicode function:

def __unicode__(self):
      return self.field_one

This works fine, because you are returning unicode string directly, no conversion needed.

Lets revisit the first unicode function, to make it work, you just need to add u to make it a unicode string

def __unicode__(self):
      return u"{0}".format(self.field_one)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.