sgdm1w
1.418K
· February 2013 ·
4b8eaf6a72ba36db1851b76ed04bee22

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.

Sign in or sign up to add your response.

2 Responses

4044
Dae3715f6eae05308ff8bd57b1618b2b

+1 for using the word "automagically" ;-)

over 1 year ago ·
16939
700a617191e43d8b29ef74257c35e761

this is basically what this package does : https://github.com/deschler/django-modeltranslation

over 1 year ago ·
Featured Programming Job

Senior Ruby on Rails Engineer
·
San Francisco
·
Full Time
Search all programming jobs