根据__unicode__
,request.session['django_language']
是否有办法返回西班牙语或英语?我应该以不同的方式设计我的模型,还是这是标准的做事方式?
class Tip(models.Model):
'''A small random tip for users to see on the login page'''
en_text = models.CharField(max_length=500)
es_text = models.CharField(max_length=500)
def __unicode__(self):
pass
然后从视图到模板......
try:
tip = Tip.objects.order_by('?')[0]
except:
tip = None
- >
<p>{{ tip }}</p>
答案 0 :(得分:1)
我不确定这是最好的方法,但我遇到了类似的情况并做了以下事情:
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
因此,如果我想要法语模型数据,我只需image.set_language('fr')
,然后在我的模板中我可以{{ image.caption }}
获取翻译版本。我不会使用__unicode__
在模板中显示模型。