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')),

No comments:

Post a Comment