Answer the question
In order to leave comments, you need to log in
How to change user language in Django site?
Hello!
I make it possible on the site to switch between the Russian, English and Ukrainian versions. I wrapped the lines in the templates that need to be translated into the {% trans %} tag, the lines in the code, translated everything and compiled the translation. Also set locale_url.
In settings.py I wrote:
LANGUAGE_CODE = 'Ru-ru'
LANGUAGES = (
('en', 'English'),
('ru', 'Russian'),
('uk', 'Ukrainian'),
)
TIME_ZONE = 'Europe/Kiev'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = (
'locale',
# os.path.join(BASE_DIR, 'locale'),
)
def select_lang(request, code):
go_next = request.META.get('HTTP_REFERER', '/')
response = HttpResponseRedirect(go_next)
if code and translation.check_for_language(code):
if hasattr(request, 'session'):
request.session['django_language'] = code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, code)
translation.activate(code)
return response
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
]
request.session['django_language']
language code that I need. Answer the question
In order to leave comments, you need to log in
Instead of 'django_language' use the constant LANGUAGE_SESSION_KEY from django.utils.translation. I think the problem is this. Now you save the language in the session under some left key. LANGUAGE_SESSION_KEY does not have this value.
from django.utils.translation import LANGUAGE_SESSION_KEY
def select_lang(request, code):
...
request.session[LANGUAGE_SESSION_KEY] = code
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question