To translate strings, you will have to create translation files. To do so, django ships with the management command makemessages
.
$ django-admin makemessages -l fr
processing locale fr
The above command will discover all strings marked as translatable within your installed apps and create one language file for each app for french translation. For instance, if you have only one app myapp
containing translatable strings, this will create a file myapp/locale/fr/LC_MESSAGES/django.po
. This file may look like the following:
# SOME DESCRIPTIVE TITLE
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-07-24 14:01+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: myapp/models.py:22
msgid "user"
msgstr ""
#: myapp/models.py:39
msgid "A user already exists with this email address."
msgstr ""
#: myapp/templates/myapp/register.html:155
#, python-format
msgid ""
"By signing up, you accept our <a href=\"%(terms_url)s\" "
"target=_blank>Terms of services</a>."
msgstr ""
You will first have to fill in the placeholders (emphasized with uppercases). Then translate the strings. msgid
is the string marked as translatable in your code. msgstr
is where you have to write the translation of the string right above.
When a string contains placeholders, you will have to include them in your translation as well. For instance, you will translate the latest message as the following:
#: myapp/templates/myapp/register.html:155
#, python-format
msgid ""
"By signing up, you accept our <a href=\"%(terms_url)s\" "
"target=_blank>Terms of services</a>."
msgstr ""
"En vous inscrivant, vous acceptez nos <a href=\"%(terms_url)s\" "
"target=_blank>Conditions d'utilisation</a>"
Once your translation file is completed, you will have to compile the .po
files into .mo
files. This is done by calling the compilemessages
management command:
$ django-admin compilemessages
That's it, now translations are available.
To update your translation files when you make changes to your code, you can rerun django-admin makemessages -l fr
. This will update .po
files, keeping your existing translations and adding the new ones. Deleted strings will still be available in comments. To update .po
files for all languages, run django-admin makemessages -a
. Once your .po
files are updated, don't forget to run django-admin compilemessages
again to generate .mo
files.