django internationalization and background switching between English and Chinese

Keywords: Django Python JSON encoding

The deployment site of the project is: China mainland and the east coast of the United States, the server data of the two regions are not synchronized, the server pages of the Chinese region are displayed in Chinese, the server pages of the American region are displayed in English, the backstage of the project is developed with python Programming language, and the version iteration is carried out with django framework.

The internationalization of the project is described here.

 

In the configuration file settings.py:

1) Open the internationalization function

# Language, first set to Chinese
LANGUAGE_CODE = 'zh-hans'  # language code settings are different after version 1.8. Before version 1.8, LANGUAGE_CODE='zh-CN'
# LANGUAGE_CODE = 'en'

# time zone
TIME_ZONE = 'Asia/Shanghai'
# TIME_ZONE = 'UTC'

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
# Opening up internationalization
USE_I18N = True

# Open localization
USE_L10N = True

USE_TZ = True

LANGUAGES = (
   ('en', 'English'),
   ('zh-hans', 'Simplified Chinese'),
)

# The directory where the translation file is located, in the same directory as the management.py file
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

2) Adding internationalized Middleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # This is the newly added middleware. Note the location: it needs to be placed behind the Session Middleware Middleware
    'django.middleware.locale.LocaleMiddleware',  
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

3) Add i18n context renderer

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # I wonder if the newly added context renderer is improperly configured. If the renderer is placed in another location, it will not be able to switch languages.
                'django.template.context_processors.i18n',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

 

2. In the project routing file urls.py, add routing:

# If you need to support the free choice of language in the page for switching, you must add the route to obtain the language translation file.
url(r'^i18n/', include('django.conf.urls.i18n')),

 

3. Open internationalization in template files

<!DOCTYPE html>

{% load i18n %}

Turn on Internationalization in templates that require internationalization: Add {% load i18n%} at the beginning of the document, or place it after <! DOCTYPE html>.

 

4. Adding strings that need to be internationalized

1) Call template in view, render template by variable assignment (or return json data directly to the front desk, translated by the front desk through js or other modules):

In views.py:

from django.utils.translation import gettext_lazy as _

    ...
    if user.is_active:
        # _ ("Activated") Indicates internationalization of the string
        context = {"text": _("Activated"),"domain": domain}
        # Template rendering, response to user requests. If the front and back are separated, you can directly return json data to the front end, which is internationalized in js
        return render(request, "./users/active_account.html", context)

If it is a template rendering, in the corresponding template file acitveacitve_account.html:

<body>
    <h2>{%trans "Hello!" %}</h2>
    <h2>{{ text }}</h2>
    <img src="{{ domain }}/static/images/qcat2.jpeg" alt="">
</body>

The variables are rendered directly into the template, and the translation files are invoked by the template for translation.

If you need to internationalize strings, you can write them to death directly in the template, or you can internationalize them directly in the template by using the following ways:

{% trans "String to be translated"%}, as shown in the code above.

 

5. Generate translation files (first create local directory under management.py's peer directory)

python manage.py makemessages -l en

A po translation file is generated in the local directory, which automatically lists the strings to be translated, such as:

# 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: 2019-04-17 03:06+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: apps/users/models.py:25
msgid "E-mail address"
msgstr ""

#: apps/users/views.py:748
msgid "Activated"
msgstr ""


#: templates/users/active_account.html:10
msgid "Hello!"
msgstr ""

msgid: Strings that need to be internationalized

msgstr: Fill in the translated string, for example:

# 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: 2019-04-17 03:06+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

msgid "E-mail address"
msgstr "email"

#: apps/users/views.py:748
msgid "Activated"
msgstr "You have successfully activated the account, do not need to activete it again, thank you!"

#: templates/users/active_account.html:10
msgid "Hello!"
msgstr "hello"

Compile the po file and execute the following commands in the local directory:

python manage.py compilemessages

At this point, the international configuration is basically completed, and the language display settings of the platform can be set up by modifying the configuration items.

# Language, first set to Chinese
LANGUAGE_CODE = 'zh-hans'  # language code settings are different after version 1.8. Before version 1.8, LANGUAGE_CODE='zh-CN'
# LANGUAGE_CODE = 'en'

# time zone
TIME_ZONE = 'Asia/Shanghai'
# TIME_ZONE = 'UTC'

As shown below

Chinese:

Hello!
Activated

 

English:

hello
You have successfully activated the account, do not need to activete it again, thank you!

 

If you need to let users choose to switch languages on the page, you need to make additional configurations. You can see the official documents for details.

 

 

Posted by poelinca on Fri, 10 May 2019 13:45:56 -0700