Django – UnicodeDecodeError using i18n

If you’re using i18n in your django website, you may encounter this issue. It took me two hours to find where the problem came from: you have to use ugettext instead of gettext if your translated strings contains non-ascii characters.

gettext => ugettext

With gettext:

1
2
3
4
5
from django.utils.translation import gettext as _

define my_view(request):
    print _("Here comes nothing") // Prints "Here comes nothing"
    print _("Here comes something spécial") // Raises a UnicodeDecodeError because "é" is not unicode

With ugettext:

1
2
3
4
5
from django.utils.translation import ugettext as _

define my_view(request):
    print _("Here comes nothing") // Prints "Here comes nothing"
    print _("Here comes something spécial") // Prints "Here comes something spécial"

ugettext or ugettext_lazy ?

Two simple rules:

  • Use ugettext_lazy in global scopes (model fields, django settings, everything not wrapped by a function or method, …)
  • Use ugettext everywhere else (in views, methods, functions, …)

That’s it !

Loïs Di Qual: I'm an iOS developer based in Bordeaux, France. This is my blog.