Quick guide about Django translation

The documentation of translation in Django is pretty well done, but quite long. If you want to setup it up easily, here are the steps.

Translation Setup

Make sure you have gettext installed on your machine. I wrote an article about the OSX specificities.

Create a locale folder inside your main project folder

Django will create subfolders in the locale folder for each language you want to support.

Make sure you include the middleware class in your settings.py file, create or modify the languages settings and set the LOCALE_PATH variable :

Depending on your project structure, you might need to change the locale path to suit your needs. It’s often the cause of the translations not working !

Translation in .py files

We create an alias to it’s easier to use and I think it makes it more readable.

We can add a special comment which will be displayed in the translation file. It can be useful for your translators.

There are a lot of other possibilities. Please read the documentation.

Translation in templates

We need to indicate that we’re using translation, so put that code somewhere near the top of your template.

Then it’s pretty easy

Again, a lot of options and other methods are available, please read the doc.

Create the language files

Fortunately, Django is doing that for us ! Let’s create the french file :

Django will create the file in mysite/locale/fr/LC_MESSAGES/django.po

It’ll look like this :

You simply have to fill out msgstr with the translated phrase.

If you add new phrases in your code, just run

It’ll update all the languages.

Now, the last step : compiling the files into .mo files (binary files optimized for gettext)

And you’re pretty much done. It’s really awesome to see how easy it is.

Published by

Louwii

Web developer, geek, car enthusiast, photographer, DIYer, video gamer... I like many things, maybe too many?

One thought on “Quick guide about Django translation”

Leave a Reply

Your email address will not be published. Required fields are marked *