Last Updated: February 25, 2016
·
555
· alvarovelezgalvez

Django template-tag to translate DB fields

Sometimes it happens that you have fields in database (commonly related to descriptions) that are translated to several languages (i.e. a table with fields like: description-en , description-es, description-de ...), and you have to show those fields in your website depending of the language chosen by users.

This is a template filter that can be called from a Django template, that returns a translated version of the field you want to show.

In Django template you will use:

{{ object_to_translate|translate_field:'description' }}

And the template filter code is:

@register.filter( name='translate_field' )
def translate_field( object_to_translate,field_to_translate ):
from django.utils.translation import get_language
    try:
        return getattr(object_to_translate, field_to_translate +'-' + get_language())
    except AttributeError:
        pass

    return ''

Depending on the language, a different 'description' field will be shown.

Salu2,
Álvaro