Thursday, October 4, 2012

Django->internationalization

I've decided to put more detailed information about multilingual pages.

So, how they are implemented in Django and how make it work. Let's do step-by-step.
0.settings.py:
add context processors, it should be something like that:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.i18n",
    "django.core.context_processors.request",
    "django.core.context_processors.media",
    "django.core.context_processors.csrf",
)


and middleware:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',   
    'django.middleware.locale.LocaleMiddleware',
)


and languages:
LANGUAGES = (
        ('ru','Russian'),
        ('en','English'),
)

 

1.Add trans or blocktrans to html you want to be transalted:
e.g., {% trans "Home" %}
2. also, add {% load i18n %} to the beginning of html (usually it's "base.html").
3. Generate dictionaries (.po):
3.1 Set PYTHONPATH (export PYTHONPATH=/path/to/your/project/)
3.2 Go to your project/application directory, create there directiry locale and execute: django-admin.py makemessages -l ru . It will generate .po files in locale/ru/LC_MESSAGES
open the file and add translation. It will look like:
#: templates/flatpages/default.html:15
msgid "About"
msgstr "О нас"

3.3 Compile the files:
django-admin.py compilemessages

If you update the files you should use:makemessages -a
4. Add form to switch languges:
html:


        {% csrf_token %}

         <input name="next" type="hidden" value="/" /> 
            <select name="language">
                             {% for lang in LANGUAGES %}
                 <option value="{{ lang.0 }}"<{{ lang.1 }}>
             {% endfor %}
              </select> 

             <input type="submit" value="Go" />
             </form>
Urls.py: (r'^i18n/', include('django.conf.urls.i18n')),

django:makemessages encoding problem

Tried to execute
 django-admin.py makemessages -l ru

Got error:
Error: errors happened while running xgettext on mogrify.py
xgettext: ./build/psycopg2/examples/mogrify.py:2: Unknown encoding "utf8". Proceeding with ASCII instead.
xgettext: Non-ASCII string at ./build/psycopg2/examples/mogrify.py:37.
          Please specify the source encoding through --from-code or through a comment
          as specified in http://www.python.org/peps/pep-0263.html.


Reason and solution:
xgettext doesn't accept 'utf8', it accepts only 'utf-8'. The same with 'latin-1', it should be replaced with 'ISO-8859-1'.

So, the solution: you should check all your files inside your project or application directory if there are 'utf8' (or 'latin-1') and replace them with 'utf-8'('ISO-8859-1').