Django auto-translation of field values
Monday, July 14th, 2008What’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.
