1
I’m not sure that this is the greatest way to do it, but I faced a similar situation and did the following:
class Image(models.Model, TranslatedModelMixin):
artifact = models.ForeignKey(Artifact)
caption = models.CharField(max_length=500, null=True, blank=True)
caption_fr = models.CharField(max_length=500, null=True, blank=True)
image = models.ImageField(upload_to='artifacts/images')
language_code = 'en'
translated_fields = ['caption']
def __unicode__(self):
return u'Image for %s' % self.artifact.name
class TranslatedModelMixin(object):
"""
Given a translated model, overwrites the original language with
the one requested
"""
def set_language(self, language_code):
if language_code == 'en':
return
self.language_code = language_code
for field in self.translated_fields:
translated_field_key = field + '_' + language_code
translated_field = getattr(self, translated_field_key)
setattr(self, field, translated_field)
return
So if I want the model data in french, I just do image.set_language('fr')
and then in my template I can just do {{ image.caption }}
and get the translated version. I wouldn’t use __unicode__
to present the model in the template.
Source:stackexchange.com