Django internationalization of the language and in English were switched in the background

The project for deployment: Mainland China and the US East Coast, server data two regions not synchronize a server in China show Chinese pages, server pages show the United States into English, project background using python programming language development, and combined with django framework version of the iteration. 

here on the international project configuration instructions: 


a configuration file in settings.py:

 1 ) open the internationalization features 

    # language, first set into Chinese 
    LANGUAGE_CODE = ' zh-Hans '   # 1.8 version after the language code set is different from before is 1.8 = LANGUAGE_CODE 'the CN-ZH' 
    # LANGUAGE_CODE = 'EN' 
     
    # time zone 
    TIME_ZONE = ' Asia / of Shanghai ' 
    # TIME_ZONE = 'UTC' 
     
    # Internationalization 
    # https://docs.djangoproject.com /en/2.1/topics/i18n/ 
    # open international 
    USE_I18N = True 
     
    #Open localization 
    USE_L10N = True 
     
    USE_TZ = True 
     
    LANGUAGES = ( 
       ( ' EN ' , ' English ' ), 
       ( ' zh-Hans ' , ' Simplified Chinese ' ), 
    ) 
     
    # translate file directory, file at the same level with manage.py directory 
    LOCALE_PATHS = ( 
        the os.path.join (base_dir, ' the locale ' ), 
    )

 2 ) was added for international middleware 

    mIDDLEWARE = [
         'django.middleware.security.SecurityMiddleware ' ,
         ' django.contrib.sessions.middleware.SessionMiddleware ' ,
         # this is a new add in middleware, note the location: SessionMiddleware middleware needs to be placed in the back 
        ' 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) 添加i18n上下文渲染器

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    #Add in the new context renderer, I do not know whether it is improper configuration, if the renderer is placed in a different location, language can not be switched 
                    ' 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 ' , 
                ], 
            }, 
        }, 
    ] 


II. routing in the project file urls.py , add routing: 

    # If you need to support the freedom to choose the language of the page to switch, you must add the route to obtain language translation files
    URL (R & lt ' ^ the i18n / ' , the include ( ' django.conf.urls.i18n ' )), 


III. in international open template file

     <! DOCTYPE HTML> 
     
    { % Load the i18n% } 

in need international template in turn internationalization features: add at the beginning of the file: { %} Load the i18n%, may also be placed in the <DOCTYPE html!> back 


four to add the string to internationalization.

 1 ) calls in a view template, a variable value assignment rendering template (or json data directly back to the front desk, translated by js or other modules from the front): 

in views.py in: 

    from django.utils.translation Import gettext_lazy AS _ 
     
        ... 
        IF user.is_active:
             # _ ( " activated ") marked international translation of the string, if it is separated from the front and rear end, use gettext_lazy() Later be translated to other languages, can be converted into json data forward station returns a 
            context = { " text " : _ ( " active " ), " Domain " : Domain}
             # template rendered in response to a user request, if the front and rear. separation, can be returned directly to the front end json data, performed by the international js front end in 
            return the render (Request, " ./users/active_account.html " , context) 

if the template is rendered in the corresponding template file in acitveacitve_account.html:

     <body> 
        <H2> {% Trans " Hello! " %} </ H2> 
        <H2> {{text}} </ H2> 
        <IMG the src = " {} {} Domain / static / Images / qcat2.jpeg" alt="" > 
    </ Body> 

directly into the template can be rendered variable by calling the template translation file for translation. 

If you need to string internationalization can be written directly to die in the template, you can use the following directly in the template international way: 

{ % Trans " translated strings " % .}, as shown in the above code 


V. generated translation file (create locale directory in the same directory manage.py) 

Python manage.py makemessages - L EN 

will generate po translation file in the locale directory, the file is automatically listed in the string needs to be translated, such as: 

    # SOME Descriptive TITLE. 
    # Copyright (C) YEAR tHE PACKAGE'S COPYRIGHT HOLDER 
    # This iS Distributed file an under at the Same, AS at The PACKAGE Package Penalty for License. 
    # 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 <[email protected]>\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 / the Users / models.py: 25 
    msgid " Email Address " 
    msgid " " 
     
    # : Apps / the Users / views.py: 748 
    msgid " activated " 
    msgid " " 
     
     
    # : Templates / the Users / active_account.html: 10 
    msgid " ! hello " 
    msgid "" 

msgid: the need for international string 

msgstr: the translated strings, you can go to fill, such as: 

    # . SOME Descriptive TITLE 
    # Copyright (C) YEAR tHE PACKAGE'S COPYRIGHT HOLDER 
    # IS at The Distributed File an under the this License AS at The Same, PACKAGE Package Penalty for. 
    # 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 <[email protected]>\n"
    "Language: \n"
    "MIME-Version: 1.0\n"
    "Content-Type: text/plain; charset=UTF-8\n"
    "Transfer-Encoding-Content: 8bit \ the n- " 
    " Plural-Forms: nplurals = 2; plural = (= the n-1!); \ The n- " 
     
    msgid " Email Address " 
    msgid " Email " 
     
    # : Apps / the Users / views.py: 748 
    msgid " activated " 
    msgid " by you at The have have successfully activated the Account, do not need to activete IT Again, Thank you! " 
     
    # : Templates / the Users / active_account.html: 10 
    msgid " ! hello " 
    msgid " the hello " 

compiled po file, execute the following command in the directory where the locale:

python manage.py compilemessages

Here, international configuration basically completed, can be the platform language display settings by modifying the following configuration item 

    # Chinese 
    LANGUAGE_CODE = ' zh-Hans '   # different language code set up after the 1.8 version before 1.8 is LANGUAGE_CODE =' zh -CN ' 
    # LANGUAGE_CODE =' EN ' 
     
    # time zone 
    TIME_ZONE = ' Asia / of Shanghai ' 
    # TIME_ZONE =' UTC ' 

as follows 

Chinese: 

    Hello! 
    activated 

English: 

    Hello 
    by You have have successfully activated The Account, do Not need to activete IT again, thank you! 

If you need to let the user choose the language switch pages, you also need additional configuration details, you can go check out the official documents
 

VI. If the foreground is APP, language switching time, because the locale has been front and back of the need to maintain, so I am here to take a not too elegant approach: an interface package, when the user switches internationalization, requested by APP at this interface, the user selects the background informing that language, the interface code as follows: 

    @api_view ([ " the POST " ])
     DEF set_lang (request):
         "" " 
        when the user switches the language App, at the request of the interface 
        : param Request: 
        : return: 
        "" " 
        Language = request.data.get ( " Language " , " EN " ) 
     
        IF Language == " ZH-Hans " : 
            makes request.session [ ' _language '] = "zh-hans" 
        The else : 
            makes request.session [ ' _language ' ] = " EN " 
     
        return the Response ({ " MSG " : " Ok " }, Status = status.HTTP_200_OK) 

when the user requests other interfaces, may request acquired by the request object to the user that is currently selected language (even without login can also get to): 

language = request.LANGUAGE_CODE

 

Guess you like

Origin www.cnblogs.com/lowmanisbusy/p/10930003.html