Quick & dirty multilingual fields in Django
If you work a multilingual site you probably have fields in your models that you need to offer in several languages. Product descriptions, for instance, should be captured in every language and displayed in the current user's one.
What I do is define description_en
, description_es
, description_fr
, etc. fields on my model, and then write a property that automagically picks the right one:
from django.utils import translation
class Product:
description_en = models.CharField()
description_es = models.CharField()
@property
def description(self):
lang = translation.get_language()
return getattr(
self, 'description_%s' % lang,
_(u'Not available')
)
Which allows me to do {{ product.description }}
in my templates and have everything just work.
Written by Jair Trejo
Related protips
2 Responses
+1 for using the word "automagically" ;-)
over 1 year ago
·
this is basically what this package does : https://github.com/deschler/django-modeltranslation
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#