Django: A Quick Guide to Internationalization

Translation of an application into different languages โ€‹โ€‹and its localization is something that all developers have to deal with. The material, the translation of which we publish today, provides a brief guide on the internationalization of Django applications.

Part of what will be discussed here applies to the localization of any Python projects. Having examined the basics, weโ€™ll talk about accelerating internationalization efforts. In particular, on the use of the Phrase platform . It is assumed that the reader of this material has a working Django application, and that he has a package installed (you can install it, for example, with a command ). If you havenโ€™t used Django (a popular Python-based web framework) before, then it might be useful for you to take a look at this first.



gettextpip install gettextofficial guide , and then return to this article.

Basic work environment settings


So, suppose you have a Django project mysite, and an application called polls. The project structure should look something like this:

/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    polls/
        migrations/
        __init__.py
        admin.py
        models.py
        tests.py
        views.py

The first step of our work is to check whether the internationalization option is activated in the project configuration. In order to do this, you need to make the following changes to mysite/settings.py:

# mysite/settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

Internationalization of templates


Now you need to mark all the lines that should be translated into different languages. Suppose you have the following template file polls/templates/polls/index.html:

<!-- polls/templates/polls/index.html -->
<h1>Welcome to our site!</h1>
<p>Here you find polls.</p>

This file needs to be processed as follows:

<!-- polls/templates/polls/index.html -->
{% load i18n %}
<h1>{% trans 'WelcomeHeading' %}</h1>
<p>{% trans 'WelcomeMessage' %}</p>

Here we imported a package for localization and replaced all the text with view constructs trans 'SomeTranslationKeyName'. In addition, as an alternative to this approach, you can use the translation texts used by default in the form of translation keys. With this approach, you will always have good default text if there is no translation available for a certain key.

Internationalization in Python Code


If you want to localize strings inside Python code (for example, in a file polls/views.py), you need to import the function into the file ugettext. To her, which is quite normal, you can assign an alias _. Here's what a localized version of a simple function from a file will look like views.py:

# polls/views.py
from django.http import HttpResponse
from django.utils.translation import ugettext as _
def index(request):
    output = _('StatusMsg')
    return HttpResponse(output)

Creating Translation Files


Now we need to create translation files for each language setting that we want to support. In order to do this, create a directory polls/localeand pollsexecute the following command in the directory :

django-admin makemessage -l de

Here deyou can replace the locale code for the language that you plan to add to the application. In our example, the execution of this command will lead to the creation of an gettext-file with the polls/locale/de/LC_MESSAGES/django.pofollowing contents:

# polls/locale/de/LC_MESSAGES/django.po
...
#: templates/polls/index.html:3
msgid "WelcomeHeading"
msgstr ""
#: templates/polls/index.html:4
msgid "WelcomeMessage"
msgstr ""

Now you can enter line feeds in this file:

# polls/locale/de/LC_MESSAGES/django.po
...
#: templates/polls/index.html:3
msgid "WelcomeHeading"
msgstr "Willkommen auf unserer Seite!"
#: templates/polls/index.html:4
msgid "WelcomeMessage"
msgstr "Hier findet Ihr Umfragen."

When the translation is ready, you need to compile everything by running the following command:

$ django-admin compilemessages

Run this command again, in the directory polls.

In order to quickly check the operability of the translation, you need to change the language code in the file mysite/settings.py. For example, like this:

# mysite/settings.py
LANGUAGE_CODE = 'de'

If you now open the application in a browser, it must be translated into German.

Speed โ€‹โ€‹up application localization using Phrase


If you use Phrase to organize work on localizing applications, then you really do not need to manually create and edit * .po files! You just need to create and transfer the keys WelcomeHeadingand WelcomeMessagein the Phrase and use the export function to download the * .po-files.

If you have our command line tool installed Phrase Client, then your work is simplified even more. It is enough to create a configuration file in the root directory of the project .phraseapp.ymlwith the following contents:

# .phraseapp.yml
phraseapp:
  access_token: <your access token>
  project_id: <your project's id on PhraseApp>
  file_format: po
  pull:
    targets:
        file: "polls/locale/<locale_code>/LC_MESSAGES/django.po

Then you need to run the following command in the root directory of the project:

phraseapp pull && django-admin compilemessages

Thanks to this, all translations of the project will be updated.

In addition, the use of our In-Context Editor in your Django project can further simplify the work . To do this, just install django-phraseusing pip:

pip install django-phrase

Then just edit the templates when working with which you plan to use In-Context-Editor:

<!-- polls/templates/polls/index.html -->
{% load i18n %}
{% load phrase_i18n %}
{% phrase_javascript %}
<h1>{% trans 'WelcomeHeading' %}</h1>
<p>{% trans 'WelcomeMessage' %}</p>

Please note that loading phrase_i18nshould be done after i18n.

Finally, add the following to the configuration file:

# mysite/settings.py
PHRASE_ENABLED = True
PHRASE_PROJECT_ID = 'YOUR_PROJECT_ID'
PHRASE_PREFIX = '{{__'
PHRASE_SUFFIX = '__}}'

After that, everything will be ready to go.

Locale selection


Typically, application developers set locales based on the user's browser settings. In order to do this, you need to bring the file mysite/settings.pyto the following form:

# mysite/settings.py
from django.utils.translation import ugettext_lazy as _
...
MIDDLEWARE_CLASSES = (
    ...,
    'django.middleware.locale.LocaleMiddleware',
    ...,
)
...
LANGUAGE_CODE = 'en-us'
LANGUAGES = (
    ('en-us', _('English')),
    ('de', _('German')),
)

With this approach, if the user has a locale German, he will see a translation option de. Otherwise, the default translation will be used en-us. You can verify the correct operation of this mechanism using curl:

curl http://localhost:8000/polls -H "Accept-Language: de"

This command should return something like the following:

<h1>Willkommen auf unserer Seite!</h1>
<p>Hier findet Ihr Umfragen.</p>

Summary


In this article, we examined the basics of internationalizing Django applications. Here we talked about the Phrase service, which is able to speed up and simplify the work. We hope that what you learned is useful to you.

Dear readers! How do you approach the internationalization of your Python projects?


All Articles