Will & Skill Developers

Will & Skill Developers


Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Erik Svedin
Author

Share


Using Django's built-in translations

Erik SvedinErik Svedin

Django comes with a great way to handle translations in your project. Whether it's static strings in your projects templates, or error messages to help developers using your fancy package, Django is here to help!

This guide covers everything you'll need to know in 3 steps, configuring your system & application, adding translations in your template and code, and of course generating the translation files.

Installing requirements and configuring django

Before you start there is one requirement other than django, the gettext package.

For debian systems:
$ sudo apt-get install gettext

For osx via brew:
$ brew install gettext

Now we need to configure our settings.py file with the following:

  1. Path to the folder where your translations will live
  2. Add the locale middleware
LOCALE_PATHS = (  
    os.path.join(BASE_DIR, 'locale'),
)
MIDDLEWARE = [  
       ...,
       'django.middleware.locale.LocaleMiddleware'
] 

Using translations in templates & code

Django comes with a built-in translation template tag. In order to use it you must make sure to load i18n.
In order to use translations in code you must import the gettext lib.

In templates

{% load i18n %}
<h1> {% trans 'welcome_to_will_and_skill' %} </h1>  

In code

from django.utils.translation import gettext as _

def get_translated_string():  
    message = _('Very important string')
    return message

Note that translation keys can contain whitespace in them like the later example.

Generating translation files

When generating the translation files django will automatically find all the places you've added translation keys in your project like we did above.

To generate a file for the locale 'sv' run the following:

python manage.py makemessages -l sv

This should create a directory 'sv' with a sub dir LC_MESSAGES containing a django.po under your specified locale directory. Add your translations by modifying the msgstr.

#: templates/my_template.html:2
msgid "welcome_to_will_and_skill"  
msgstr "Välkommen till Will & Skill"  

When you've added all your message strings you will need to run the compilemessages command in order for django to use them.

$ python manage.py compilemessages

And vóila! You're now up and running with django translations. Happy coding!

For further reading check out the offical docs:
https://docs.djangoproject.com/en/1.10/topics/i18n/translation/

Erik Svedin
Author

Erik Svedin

Comments