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.
July 22nd, 2008 at 2:50 pm
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
July 22nd, 2008 at 8:00 pm
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! =)
March 6th, 2010 at 6:28 pm
Thanks for your article. I am new at python and this was a big help.