1 |
|
---|
2 | from django.utils.translation import get_language
|
---|
3 |
|
---|
4 | from django.conf import settings
|
---|
5 |
|
---|
6 | available_languages = settings.LANGUAGES
|
---|
7 | TRANSLATION = lambda name, code: str('%s_%s' % (name, code))
|
---|
8 |
|
---|
9 | class 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 |
|
---|
28 | class TranslatedCharField(BaseTranslatedField, models.CharField):
|
---|
29 | def get_base_model(self):
|
---|
30 | return models.CharField
|
---|
31 |
|
---|
32 | class TranslatedTextField(BaseTranslatedField, models.TextField):
|
---|
33 | def get_base_model(self):
|
---|
34 | return models.TextField
|
---|
35 |
|
---|
36 |
|
---|
37 | /* SAMPLE USAGE */
|
---|
38 |
|
---|
39 | class MultiLanguage(models.Model):
|
---|
40 | name = TranslatedCharField(max_length = 255, verbose_name = _('name'))
|
---|
41 | description = TranslatedTextField(null = True, blank = True,
|
---|
42 | verbose_name = _('description'))
|
---|
43 |
|
---|
44 | def __unicode__(self):
|
---|
45 | return self.name()
|
---|
46 |
|
---|
47 | class Meta:
|
---|
48 | ordering = 'name_%s' % get_language(),
|
---|
49 |
|
---|
50 |
|
---|
51 | myobj= MultiLanguage(
|
---|
52 | name_it = 'Tavolo',
|
---|
53 | name_en = 'Table',
|
---|
54 | description_it = 'Usato per mangiare',
|
---|
55 | description_en = 'Used to eat'
|
---|
56 | )
|
---|
57 |
|
---|
58 | myobj.name()
|
---|
59 | #returns 'Tavolo', if the current lang is IT
|
---|
60 |
|
---|
61 | myobj.description()
|
---|
62 | #returns 'Usato per mangiare', if the current lang is IT
|
---|