Django auto-translation of field values

What’s really nice in Django is the gettext implementation and the _ convention. But when running django-admin.py makemessages we’re not generating any translations for dynamic values such as field values. So let’s say that we have a model and we’d like what’s in it to be displayed in a translated manner. In the new Django development version we’re able to create our own special field types. And we can extend the CharField to provide automatic translation:

1
2
3
4
5
6
7
from django.db import models
from django.utils.translation import gettext_lazy as _
 
class AutoTranslateField(models.CharField):
    __metaclass__ = models.SubfieldBase
    def to_python(self, value):
        return str(_(value))

After that we just add whatever translations we know of to our locale/CODE/LC_MESSAGES/django.po file and run compilemessages.

3 Responses to “Django auto-translation of field values”

  1. Nick Says:

    Hello!

    Are you sure to return value in str?
    return str(_(value))

    May be it’s more safe to return it like that:
    return unicode(_(value))

    WBR,
    Nick

  2. benjamin Says:

    That depends. I wrote “from django.utils.translation import gettext_lazy as _” and that’s the one returning ascii. If you import ugettext, then it will return unicode. I’m not sure, but you’re most likely right that to_python() should return the same encoding as the rest of the model.. so yes! =)

  3. Laurie Carlin Says:

    Thanks for your article. I am new at python and this was a big help.

Leave a Reply