Tutorial on setting language preferences in the Django framework

Source: Internet
Author: User
Once you have the translation ready, if you want to use it in Django, you just need to activate the translation.

Behind these features, Django has a flexible model to determine which language to use during the installation and use of the application.

To set a language preference for the installation phase, please set language_code. If another translator does not find a translation, Django will use this language as the default translation final attempt.

If you just want to run Django in the local language and the language file exists, simply set the Language_code.

If you want each user to specify a language preference, you need to use Localemiddleware. Localemiddleware enables Django to customize content for each user by making the language selection based on the requested data. It customizes content for every user.

Using localemiddleware requires adding ' django.middleware.locale.LocaleMiddleware ' to the middleware_classes settings. The order of the middleware is influential, preferably in accordance with the following requirements:

Ensure that it is the first batch of middleware classes installed.

Because Localmiddleware to use the session data, it needs to be placed after sessionmiddleware.

If you use Cachemiddleware, put the localemiddleware behind it.

For example, middle_classes might be the case:

middleware_classes = (  ' django.contrib.sessions.middleware.SessionMiddleware ',  ' Django.middleware.locale.LocaleMiddleware ',  ' django.middleware.common.CommonMiddleware ',)

Localemiddleware determines the user's language according to the following algorithm:

    • First, find the Django_language key in the current user's session;
    • If not found, it will search for a cookie
    • If it is not found, it will look for accept-language in the HTTP request header, which is sent by your browser and tells the server your language preference in order of precedence. Django will try every language in the head until it finds a usable translation.
    • If all of the above fails, use the global Language_code setting value.

Note:

In each of these places, language preference should appear as a string in a standard language format. For example, Brazilian Portuguese is PT-BR

If a basic language exists and the sub-language is not specified, Django will use the basic language. For example, if the user specified De-at (Australian German) but Django only translated for de, then de would be chosen.

Only the languages listed in the LANGUAGES settings can be selected. If you want to restrict the language to something in the provided language (because the application does not provide a representation of all languages), set LANGUAGES to the list of languages that you want to provide, for example:

LANGUAGES = ((' De ', _ (' German ')), (' En ', _ (' 中文版 ')),)

The above example restricts language preferences to only German and English (including their sub-languages, such as De-ch and en-us).

If you have customized LANGUAGES, it is possible to mark the language as a translation string, but do not use GetText () in django.utils.translation (never import in Settings file) Django.utils.translation, because the module itself is dependent on settings, which results in an infinite loop), instead uses a "fictional" gettext ().

The solution is to use a "fake" gettext (). Here is an example of a settings file:

Ugettext = Lambda S:slanguages = (  (' De ', ugettext (' German ')),  (' en ', ugettext (' 中文版 ')),)

In doing so, make-messages.py will still look for and mark the strings that will be translated, but the translation will not be performed at runtime, and therefore need to be "real" ugettext () in any code that uses LANGUAGES.

Localemiddleware can only choose the language that Django has provided for basic translation. If you want to provide translations in your application for a language that does not yet have basic translations in Django, you must provide at least a basic translation of that language. For example, Django uses a specific information ID to translate date and time formats, so that the system works properly, at least to provide these basic translations.

Based on the English. po file, the translation of the technology-related information may also include some information to make it effective.

Technology-related information IDs are easily recognized: they are all capitalized. The translation of these information IDs differs from other information: you need to provide their localized content. For example, for Datetime_format (or Date_format, Time_format), you should provide a formatted string that you want to use in that language. The format is used by the template label now to identify the format string.

Once localemiddleware determines the user's preferences, it makes this preference a request. Language_code is effective for every httprequest. Please feel free to read this value in your view code. Here is a simple example:

def hello_world (Request):  if request. Language_code = = ' De-at ':    return HttpResponse ("You prefer to read Austrian German.")  else:    return HttpResponse ("prefer to read another language.")

Note that for static translations (without middleware), this language is settings. Language_code, and for dynamic translation (middleware), it is in request. The Language_code.
Use translations in your own projects

Django uses the following algorithms to find translations:

    • First, Django looks for the locale directory in the application folder where the view resides. If a translation is found for the selected language, the translation is loaded.
    • In the second step, Django looks for the locale directory in the project directory. If a translation is found, the translation is loaded.
    • Finally, Django uses the basic translation in the Django/conf/locale directory.

In this way, you can create an application that contains a standalone translation that can overwrite the basic translation in the project. Alternatively, you can create a large project with several applications and put all the required translations in a large project information file. The decision is in your hands.

All information vaults are organized in the same way:

  $APPPATH/locale/
 
  
   
  /lc_messages/django. PO|MO)  $PROJECTPATH/locale/
  
   
    
   /lc_messages/django. ( PO|MO)
  
   
 
  

All paths listed in Locale_paths in the settings file are searched for/lc_messages/django in the order in which they are listed . ( PO|MO)

  $PYTHONPATH/django/conf/locale/
 
  
   
  /lc_messages/django. PO|MO)
 
  

To create an information file, use the django-admin.py makemessages.py tool as well as the Django information file. All you need to do is go to the correct directory--conf/locale (in the case of the source tree) or locale/(in the case of application information or project information). Similarly, use compile-messages.py to generate GetText django.mo files that need to be used by the binary.

You can also run django-admin.py compilemessages--settings=path.to.settings to enable the compiler to handle all directories that exist in your locale_paths settings.

Application information files are a little hard to find-because they require localemiddle. If you don't use middleware, Django only processes Django information files and project information files.

Finally, the structure of the translation file needs to be considered. If the application is to be distributed to other users and applied to other projects, it may be necessary to use application-related translations. However, using application-related translations and project translations can create wacky problems when using Make-messages. It iterates through all the folders under the current path, which may duplicate the message ID that exists in the application message file into the project message file.

The easiest solution is to store an application that is not part of the project (and therefore accompanying its own translation) outside the project tree. By doing so, project-level make-messages will only translate the exact relevance of the project, not the strings in the standalone published application.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.