Ticket #9601: translation.py

File translation.py, 1.8 KB (added by Riccardo Di Virgilio, 16 years ago)
Line 
1
2from django.utils.translation import get_language
3
4from django.conf import settings
5
6available_languages = settings.LANGUAGES
7TRANSLATION = lambda name, code: str('%s_%s' % (name, code))
8
9class BaseTranslatedField:
10 def __init__(self, *args, **kwargs):
11 self.base_args = args
12 self.base_kwargs = kwargs
13
14 def contribute_to_class(self, cls, name):
15 model = self.get_base_model()
16 current = TRANSLATION(name, get_language())
17
18 for code, description in available_languages:
19 cls.add_to_class(TRANSLATION(name, code), model(*self.base_args,**self.base_kwargs))
20
21 get_current = lambda self:getattr(self, current)
22 get_current.admin_order_field = current
23 cls.add_to_class(name, get_current)
24
25 #del self.base_args
26 #del self.base_kwargs
27
28class TranslatedCharField(BaseTranslatedField, models.CharField):
29 def get_base_model(self):
30 return models.CharField
31
32class TranslatedTextField(BaseTranslatedField, models.TextField):
33 def get_base_model(self):
34 return models.TextField
35
36
37/* SAMPLE USAGE */
38
39class MultiLanguage(models.Model):
40 name = TranslatedCharField(max_length = 255, verbose_name = _('name'))
41 description = TranslatedTextField(null = True, blank = True,
42 verbose_name = _('description'))
43
44def __unicode__(self):
45 return self.name()
46
47class Meta:
48 ordering = 'name_%s' % get_language(),
49
50
51myobj= MultiLanguage(
52 name_it = 'Tavolo',
53 name_en = 'Table',
54 description_it = 'Usato per mangiare',
55 description_en = 'Used to eat'
56 )
57
58myobj.name()
59#returns 'Tavolo', if the current lang is IT
60
61myobj.description()
62#returns 'Usato per mangiare', if the current lang is IT
Back to Top