Where developers come to connect, share, build and be inspired.

2

Quick & dirty multilingual fields in Django

1308 views


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.

Comments

Add a comment