2 Utilities for creating multilingual fields in your apps.
6 from django.conf import settings
7 from django.utils.translation import get_language, string_concat
10 def field_getter(name):
13 val = getattr(self, "%s_%s" % (name, get_language()), None)
15 val = getattr(self, "%s_%s" % (name, settings.LANGUAGE_CODE))
20 def add_translatable(model, fields, languages=None):
21 """Adds some translatable fields to a model, and a getter."""
23 languages = settings.LANGUAGES
24 for name, field in fields.items():
25 for lang_code, lang_name in languages:
26 new_field = copy(field)
27 if field.verbose_name:
28 new_field.verbose_name = string_concat(field.verbose_name, ' [%s]' % lang_code)
29 new_field.contribute_to_class(model, "%s_%s" % (name, lang_code))
30 setattr(model, name, field_getter(name))
34 def add_translatable_index(index_class, fields, languages=None):
35 """Adds some translatable fields to a search index."""
37 languages = settings.LANGUAGES
38 for name, field in fields.items():
39 for lang_code, lang_name in languages:
40 new_field = copy(field)
41 fname = "%s_%s" % (name, lang_code)
42 new_field.index_fieldname = new_field.index_fieldname \
43 and "%s_%s" % (new_field.index_fieldname, lang_code) \
45 new_field.model_attr = new_field.model_attr \
46 and "%s_%s" % (new_field.model_attr, lang_code) \
48 setattr(index_class, fname, new_field)
49 index_class.fields[fname] = new_field
52 def translated_fields(field_names, languages=settings.LANGUAGES):
53 """Generate a tuple of field names in translated versions."""
54 return tuple("%s_%s" % (field_name, lang_code)
55 for field_name in field_names
56 for lang_code, lang_name in languages