[Fixed]-Django internationalization minimal example

12👍

Django collects translations in these 3 ways explained here:
https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-translations

The directories listed in LOCALE_PATHS have the highest precedence, with the ones appearing first having higher precedence than the ones appearing later.

Then, it looks for and uses if it exists a locale directory in each of the installed apps listed in INSTALLED_APPS. The ones appearing first have higher precedence than the ones appearing later.

Finally, the Django-provided base translation in django/conf/locale is used as a fallback.

Since your translation file is in none of these places you need to set it manually using LOCALE_PATHS as explained here:
https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOCALE_PATHS

27👍

1º Enable Internationalization in settings.py:

USE_I18N = True

2º On settings, import:

from django.utils.translation import ugettext_lazy as _

3º Set the languages that you are going to use in settings.py:

LANGUAGES = (
    ('en', _('English')),
    ('pt-br', _('Portuguese')),
    ('it', _('Italian')),
    ('fr', _('French')),
    ('es', _('Spanish')),
)

3º Configure the LOCALE_PATH in settings.py too:

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'conf/locale'),
)

4º Inside the path you configured in LOCALE_PATH create the folders, ex:

$ cd django_project_folder
$ mkdir conf
$ mkdir conf/locale

5º Run the command:

django-admin.py makemessages -a

It will create a file .po inside a subfolder of each language set in settings.py LANGUAGES. Make the translations of each sentence inside the file.

Ps: Runs over the entire source tree of the current directory and pulls out all strings marked for translation.

For test, before run, put the tag

{% trans "Welcome to my project!" %} 

inside your index.html and run the command makemessages again. You’ll see inside de .po files a new string:

msgid "Welcome to my Project"
msgstr ""

6º Now, run the command:

django-admin compilemessages

It will collect all msgstr from .po file and will compile in a .mo file

7º Run the project and test

8ª Plus: If you want that in URL show what language the user is using you can configure your url.py to show that:

urlpatterns += i18n_patterns(
    # your urls here,
)

Leave a comment