This site runs best with JavaScript enabled.

Django smart_unicode

Django smart_unicode Django smart_unicode

Photo by JJ Ying on Unsplash

So my QA guy is putting an app through the ringer and presented me with the following error on a page:

Caught UnicodeEncodeError while rendering: ('ascii', u'Utf8-\u010a\u010e\ufffd"\u0117', 5, 8, 'ordinal not in range(128)')

For some reason I thought UTF8 characters Just Worked™ in Django, but that was a bad assumption. The problem came from my model's unicode def:

def unicode(self):
    return " ".join([self.first_name, self.last_name])

Luckily Django provides a simple fix for this problem.

from django.utils.encoding import smart_unicode

def unicode(self):
    return smart_unicode(" ".join([self.first_name, self.last_name]))
Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.