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, verbose_name = _('description'))
|
---|
42 |
|
---|
43 | def __unicode__(self):
|
---|
44 | return self.name()
|
---|
45 |
|
---|
46 | class Meta:
|
---|
47 | ordering = 'name_%s' % get_language(),
|
---|
48 | abstract = True
|
---|