Search code examples
djangointernationalizationlocale

Internationalization, some problems with switching languages


I have a site in English and want to add Russian. settings.py

LANGUAGE_CODE = 'en'

LANGUAGES = ( ('en', ('English')), ('ru', ('Russian')), )

MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', )

urls.py

url(r'^i18n/', include('django.conf.urls.i18n')),

Simple form grom django docs

> <form action="/i18n/setlang/" method="post" id="language-select">
>        <input name="next" type="hidden" value="/" />
>             {% csrf_token %}
>             <select name="language">
>                 {% for lang in LANGUAGES %}
>                     <option value="{{ lang.0 }}">{{ lang.1 }}</option>
>                 {% endfor %}
>             </select>
>        <input type="submit" value="Go" /> </form>

I install gettext, add 'locale' folder (in project folder, near manage.py). Create 'ru folder' with .po file and add some translations. But after language changing it returns [26/Jul/2013 13:43:32] "POST /i18n/setlang/ HTTP/1.1" 302 0 and redirect to English page. What's wrong here?


Solution

  • You have to put django.middleware.locale.LocaleMiddleware after django.contrib.sessions.middleware.SessionMiddleware and before django.middleware.common.CommonMiddleware

    Example:

    MIDDLEWARE_CLASSES = (
       'django.contrib.sessions.middleware.SessionMiddleware',
       'django.middleware.locale.LocaleMiddleware',
       'django.middleware.common.CommonMiddleware',
    )
    

    https://docs.djangoproject.com/en/dev/topics/i18n/translation/#how-django-discovers-language-preference