Technorati tags: django, i18n, javascript, Chinese, multi-language
Django's internationalization support is very good and easy to use. It supports code, templates, and JS internationalization solutions. Especially in version 1.2
Local formatting of dates and numbers has been well-developed for internationalization.
Application Method
First, modify settings. py:
1. Add TEMPLATE_CONTEXT_PROCESSORS to django. core. context_processors.i18n.
2. Add django. middleware. locale. LocaleMiddleware to MIDDLEWARE_CLASSES. Note: it should be placed in SessionMiddleware andThe back of CacheMiddleware and the front of other Middleware
3. Set the default website language for LANGUAGE_CODE, such as en, zh-cn,It,De-,Es,Pt-br
4. Ages sets all LANGUAGES supported by the website, such as ('en', u'inc'), ('zh-cn', u'chine '))
5. Set USE_I18N to True.
Application in code:
1. The gettext: from django. utils. translation import ugettext_lazy as _ function should be introduced to all source files that require international support _
2. For example, name = models. CharField (_ ('name ')...)
Application in the template:
1. All template files that require internationalization support need to be loaded:{% Load i18n %}
2. You need to write the strings supported by multiple languages as follows: <title >{% trans "This is the title." %} </title>
3. Sentence with variable in Translation: {% blocktrans %} This string will have {value }}inside. {% endblocktrans %}
JS applications (this part is not found in django's documentation, and I have figured out a method through the source code. You can also refer to this document ):
1. Add: (R' ^ jsi18n /(? P <packages> \ S + ?) /$ ', 'Django. views. i18n. javascript_catalog '),
This tells the page that the script is generated by the javascript_catalog function on the server when loading this script. The specific method is to find locale through packages and then find the mo file, then, all the translation strings are put into a dictionary variable in the generated script, and the script also defines the gettext function, so that the client script can use the gettext method to directly retrieve the translation string from the dictionary.
Packages lists your project names or Application names separated by plus signs. Format: testproject + testproject. app1 + testproject. app2. These projects or applications should be stated in INSTALLED_APPS.
2. Reference jsi18n: <script type = "text/javascript" src = "/jsi18n/testproject + testproject. app1 + testproject. app2"> </script>
My project is not large. I only have the locale directory under the project directory. Therefore, you can write it in this way. <script type = "text/javascript" src = "/jsi18n/testproject"> </script>
If your project is large, you can consider placing the locale directory in the Application, such as writing a script link. In this way, you do not need to generate and load the full-site JS translation string every time to speed up the process.
3. Use the gettext function translation in JS: document. write (gettext ('this is to be translated '));
4. translate sentences with variables
fmts = ngettext('There is %s object. Remaining: %s', 'There are %s objects. Remaining: %s', 11);
s = interpolate(fmts, [11, 20]); // s is 'There are 11 objects. Remaining: 20'
Generate po and mo files
Here, we need to make up the course. The first is the locale directory. Please create locale in the project directory or the Application directory. Its structure
locale
en
LC_MESSAGES (django. po/mo, djangojs. po/mo under this directory)
zh-cn
LC_MESSAGES (django. po/mo, djangojs. po/mo under this directory)
Django. po/djangojs. po is equivalent to a resource file, which is compiled to form the django.mo/djangojs.mofile and read at runtime.
You can use the poedit tool to edit po files. I personally prefer mangage. py makemessages-a to allow django to automatically analyze source code and template files.
Generate po. Pay attention to the following two points:
1. According to my practice, the po cannot be automatically generated for strings in js, and must be manually generated.
2. You need to call the tool xgettext for makemessages. It is not available for Windows. You can download the dizzy version of gettext, which requires two files.Gettext-runtime-X.zipAndGettext-tools-X.zip
X is the version number. if the version is earlier, the error "Django internationalization requires GNU gettext 0.15 or newer" will be reported ")
Decompress the package to a directory, and add the following bin directory to your system path.
3. After mangage. py makemessages-a is automatically generated, You need to edit the po file, such as zh-cn/LC_MESSAGES/djang. po.
The translation is written one by one. Last step: Compile mange. py compilemessages
Allows users to switch languages on the page
Put this in urls. py: (r '^ i18n/', include ('django. conf. urls. i18n '))
Make a form and submit the language selected by the user, for example
<form action="/i18n/setlang/" method="post"> {% csrf_token %}
<input name="next" type="hidden" value="/next/page/" />
<select name="language"> {% for lang in LANGUAGES %} <option value="{{ lang.0 }}">{{ lang.1 }}</option> {% endfor %} </select> <input type="submit" value="Go" />
</form>
This involves a question: can the language selected by the user be remembered? You do not need to select another language for the next visit? First, you need to understand how django determines the language required by the user. The judgment process is as follows:
1. First, determine whether the Session contains data with a key value of django_language. If yes, use it. (If the website supports Session when you select a language, django records your language preferences in the Session; otherwise, the Session is recorded in the cookie)
2. Check whether the cookie has settings. Your age_cookie_name. If yes, use it.
3. Check whether the Accpet Language provided by the browser is supported by the website (whether there are corresponding translation files ).
4. If none of the preceding methods are correct, use settings. LANGUAGE_CODE (default website language)
Note that this method can automatically select a language for the user based on the user's browser settings, you can also ensure that the selected language is used for the next access (the user's language is saved in the Session and a valid cookie ). If your browser settings are different from the selected language, you will not be able to use the selected language the next time you visit. To solve this problem, you can take over the processing of the URL "/i18n/setlang/", save the user's choice directly in the cookie, and the lifecycle should be longer. Example:
def set_language(request):
from django.utils.translation import check_for_language
next = request.REQUEST.get('next', None)
if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
lang_code = request.POST.get('language', None)
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session['django_language'] = lang_code
max_age = 60*60*24*365
expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, max_age, expires)
return response
Finally, change the url configuration to the following: (r '^ i18n/setlang', 'yourproject. yourapp. views. set_language '),