add app settings
[fnpdjango.git] / fnpdjango / utils / models / translation.py
1 """
2 Utilities for creating multilingual fields in your apps.
3 """
4
5 from copy import copy
6 from django.conf import settings
7 from django.utils.translation import get_language, string_concat
8
9
10 def field_getter(name):
11     @property
12     def getter(self):
13         val = getattr(self, "%s_%s" % (name, get_language()), None)
14         if not val:
15             val = getattr(self, "%s_%s" % (name, settings.LANGUAGE_CODE))
16         return val
17     return getter
18
19
20 def add_translatable(model, fields, languages=None):
21     """Adds some translatable fields to a model, and a getter."""
22     if languages is None:
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))
31         # add setter?
32
33
34 def add_translatable_index(index_class, fields, languages=None):
35     """Adds some translatable fields to a search index."""
36     if languages is None:
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) \
44                 or fname
45             new_field.model_attr = new_field.model_attr \
46                 and "%s_%s" % (new_field.model_attr, lang_code) \
47                 or fname
48             setattr(index_class, fname, new_field)
49             index_class.fields[fname] = new_field
50
51
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
57                 )