Tutorial on setting language preferences in Django framework

Source: Internet
Author: User
This article mainly introduces how to set language preferences in the Django framework. Django is the most popular Python framework. If you need a friend, refer to it. Once you have prepared a translation, if you want to use it in Django, you only need to activate these translations.

Behind these features, Django has a flexible model to determine the language used when installing and using applications.

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

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

To allow each user to specify their preferred language, use LocaleMiddleware. LocaleMiddleware enables Django to select the language based on the requested data, so as to customize the content for each user. It customizes content for each user.

To use LocaleMiddleware, add 'django. middleware. locale. LocaleMiddleware 'to the MIDDLEWARE_CLASSES settings '. The order of middleware has an impact. It is best to follow the following requirements:

Make sure it is the first batch of installed middleware class.

Because LocalMiddleware uses session data, it must be placed after SessionMiddleware.

If you use CacheMiddleware, put LocaleMiddleware behind it.

For example, MIDDLE_CLASSES may be like this:

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, search for the django_language key in the current user's session;
  • If not found, it will look for a cookie
  • If it cannot be found, it will search for Accept-Language in the HTTP Request Header, which is sent by your browser and tells the server your Language preferences in priority. Django tries every language in the header until it finds an available translation.
  • If none of the preceding operations fail, the global aggregage_code value is used.

Note:

In each of the above fields, the preferred language should be used as a string and appear in a standard language format. For example, the Brazilian Portuguese is pt-br

If a basic language exists and the sub-language is not specified, Django uses the basic language. For example, if you specify de-at (Australian German) But Django only translates de, de will be selected.

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

LANGUAGES = ( ('de', _('German')), ('en', _('English')),)

The preceding example limits the language preferences to only German and English (including their sub-languages such as de-ch and en-us ).

If you have customized ages, you can mark the language as a translation string. However, do not use django. utils. gettext () in translation (do not import django in the settings file. utils. translation, because this module itself depends on settings, this will lead to an infinite loop), but uses a "fictitious" gettext ().

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

ugettext = lambda s: sLANGUAGES = (  ('de', ugettext('German')),  ('en', ugettext('English')),)

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

LocaleMiddleware can only select languages where Django already provides basic translation. If you want to provide translation for a language without basic translation in Django in an application, you must at least provide the basic translation for that language. For example, Django uses a specific information ID to translate the date and time formats. Therefore, to make the system work properly, at least provide these basic translations.

Based on English. po documents, the translation of technical information may also include information that makes it take effect.

The technology-related information IDs are easily recognized: they are all in uppercase. The translation of these information IDS is different from other information: You need to provide the corresponding localized content. For example, for DATETIME_FORMAT (or DATE_FORMAT, TIME_FORMAT), you should provide the formatted string you want to use in this language. The format is used by the template label now to identify the format string.

Once LocaleMiddleware determines a user's preference, it will make this preference valid for each HttpRequest as request. LANGUAGE_CODE. Read this value in your view code at will. The following 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("You prefer to read another language.")

Note: For static translation (without middleware), this language is in settings. LANGUAGE_CODE, and for dynamic translation (middleware), it is in request. LANGUAGE_CODE.
Use translation in your own project

Django uses the following algorithms for translation:

  • First, Django looks for the locale directory in the application folder where the view is located. If the translation of the selected language is found, the translation is loaded.
  • Step 2: Find 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 independent translations and overwrite the basic translations in the project. Alternatively, you can create a large project that contains several applications and put all the required translations in a large project information file. You have the right to decide.

All information file libraries are organized in the same way: they are:

  $APPPATH/locale/
 
  /LC_MESSAGES/django.(po|mo)  $PROJECTPATH/locale/
  
   /LC_MESSAGES/django.(po|mo)
  
 

All the paths listed in LOCALE_PATHS in the settings file are searched in the order listed. /LC_MESSAGES/django. (po | mo)

  $PYTHONPATH/django/conf/locale/
 
  /LC_MESSAGES/django.(po|mo)
 

To create an information file, you also use the django-admin.py makemessages. py tool, just like the Django information file. You need to enter the correct directory-conf/locale (in the case of the source code tree) or locale/(in the case of application information or project information. Similarly, use the compile-messages.py to generate the binary django.mo file that gettext requires.

You can also run the django-admin.py compilemessages -- settings = path. to. settings to make the compiler 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 do not use middleware, Django only processes Django information files and project information files.

Finally, consider the structure of the translation file. If an application is to be distributed to another user, you may need to use application-related translation for the application to be applied to other projects. However, the use of application-related translation and project translation may cause odd problems when using make-messages. It traverses all folders in the current path, which may put the message IDs in the application message file into the project message file.

The easiest solution is to store apps that do not belong to the project (therefore, with their own translations attached) outside the project tree. In this way, the project-level make-messages will only translate the exact relevance of the project, not the strings in those independently published applications.

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.