Tusk Tusk - 1 year ago 106
Python Question

Django language change not working

I'm using Django 1.6, and I feel like I'm missing something, but cookies are set to current language chosen, but the display language stays the default.

Corresponding code:

settings.py

LANGUAGES = (
('hu', 'Hungarian'),
('en', 'English'),
)

TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request"
)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware'
)
LANGUAGE_CODE = 'en-US'
TIME_ZONE = 'CET'
USE_I18N = True
USE_L10N = True
USE_TZ = True


urls.py

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


template

{% extends 'base.html' %}
{% load i18n %}
...
<h4>{% trans "Modern Technologies" %}</h4>
...


I ran makemessages -a to create the lang files, rosetta is installed and languages are edited. Then I've ran compilemessages. Checking in Chrome the cookie "django_language" get's set correctly. But the actual text is still the default "Modern Technologies".

Answer Source

Your middleware order is different from that recommended by the documentation:

To use LocaleMiddleware, add 'django.middleware.locale.LocaleMiddleware' to your MIDDLEWARE_CLASSES setting. Because middleware order matters, you should follow these guidelines:

  • Make sure it’s one of the first middlewares installed.
  • It should come after SessionMiddleware, because LocaleMiddleware makes use of session data. It should also come before CommonMiddleware because CommonMiddleware needs an activated language in order to resolve the requested URL.
  • If you use CacheMiddleware, put LocaleMiddleware after it.

So your middleware configuration should look like this:

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

EDIT: You also need to remember to include the LOCALE_PATHS setting in your settings file:

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download