[Solved]-Django: How to add Chinese support to the application

18👍

You will need to use lower case for your locale language codes for it to work properly. i.e. use

LANGUAGES = (
    ('zh-cn', u'简体中文'), # instead of 'zh-CN'
    ('zh-tw', u'繁體中文'), # instead of 'zh-TW'
)

See the language codes specified in https://code.djangoproject.com/browser/django/trunk/django/conf/global_settings.py. You will see that it uses zh-tw instead of zh-TW.

Finally, the language directories storing the *.po and *.mo files in your locales folder needs to be named zh_CN and zh_TW respectively for the translations to work properly.

12👍

For Django 1.7 and up, you’ll need to do the following:

zh-hans in your config, and make sure that your directory is named zh_Hans.

And for traditional Chinese:

zh-hant in your config, and your directory should be named zh_Hant.

Here is an example of how the auth contributor package lays out its translations in the locale directory: https://github.com/django/django/tree/master/django/contrib/auth/locale

Basically, for our Chinese language codes, the - is replaced with a _, and the first letter of the second work is capitalized.

Source code for this logic is here: https://github.com/django/django/blob/7a42cfcfdc94c1e7cd653f3140b9eb30492bae4f/django/utils/translation/init.py#L272-L285

and just to be thorough, here is the method:

def to_locale(language, to_lower=False):
    """
    Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
    True, the last component is lower-cased (en_us).
    """
    p = language.find('-')
    if p >= 0:
        if to_lower:
            return language[:p].lower() + '_' + language[p + 1:].lower()
        else:
            # Get correct locale for sr-latn
            if len(language[p + 1:]) > 2:
                return language[:p].lower() + '_' + language[p + 1].upper() + language[p + 2:].lower()
            return language[:p].lower() + '_' + language[p + 1:].upper()
    else:
return language.lower()

Note that en-us is turned into en_US, based on the source code above, because us is 2 characters or less.

2👍

I had the same problem [Django-1.6.1] and solved it by renaming the locale directories for Chinese from zh-cn (or zh_cn) to zh_CN (underscore and uppercase CN).

Strangely enough Django requires a “zh-cn” as LANGUAGE_CODE or url with an i18n_pattern respectively.

Non-documented goodness btw.

Hope that helps.

1👍

Not sure if you were able to resolve this later, but the problem is with the language directory names in the locale directory. This happens with all languages with a dash in their short-code. The solution is to rename the Chinese directories by replacing the dashes with underscores:

zh-cn –> zh_cn
zh-tw –> zh_tw

Hope this helps.

1👍

In .po file, add zh-cn or zh-tw in “Language: \n”, which becomes “Language: zh-en\n” or “Language: zh-tw\n”

Compile the messages and runserver again.

Leave a comment