This site runs best with JavaScript enabled.

Django smart_unicode

Photo by JJ Ying on Unsplash

Use Django's smart_unicode function to solve unicode errors

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:

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

Luckily Django provides a simple fix for this problem.

1from django.utils.encoding import smart_unicode
3def unicode(self):
4 return smart_unicode(" ".join([self.first_name, self.last_name]))

Discuss on TwitterEdit post on GitHub

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.

Join the Newsletter

Dustin Davis