How to explicitly set django_language in django session

And if you will use a version >= Django 1.8. Here it is how we could use that:

from django.utils.translation import LANGUAGE_SESSION_KEY

def someview (request):
    ...
    request.session[LANGUAGE_SESSION_KEY] = 'en'

If you want your users to be able to specify language, make sure that LocaleMiddleware is enabled:

MIDDLEWARE_CLASSES = (
   ...
   'django.middleware.locale.LocaleMiddleware',
   ...
)

Then Django will look for the user's language preference in that order (see get_language_from_request in trans_real.py):

  1. in request.path_info, if i18n_patterns are used
  2. request.session[settings.LANGUAGE_SESSION_KEY] (DEPRECATED in Django 3.0, removed in Django 4.0)
  3. request.COOKIES[settings.LANGUAGE_COOKIE_NAME]
  4. every language in request.META['HTTP_ACCEPT_LANGUAGE'], until accepted one is found
  5. settings.LANGUAGE_CODE.

As of Django 4.0

The most straightforward way to set language explicitly in Django session is to activate and set the cookie, see the docs:

from django.conf import settings
from django.http import HttpResponse
from django.utils import translation

user_language = 'fr'  # example
translation.activate(user_language)

# persist using the cookie
response = HttpResponse(...)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)

Before Django 4.0

The most straightforward way to set language explicitly in Django session is to rewrite request.session[settings.LANGUAGE_SESSION_KEY]:

def someview (request):
    ...
    request.session[settings.LANGUAGE_SESSION_KEY] = 'en'
    ...

Consider using django.views.i18n.set_language(). Activate this view by adding the following line to your URLconf:

# This example makes the view available at /i18n/setlang/
url(r'^i18n/', include('django.conf.urls.i18n')),

As a convenience, Django comes with a view, django.views.i18n.set_language(), that sets a user’s language preference and redirects to a given URL or, by default, back to the previous page.

The view expects to be called via the POST method, with a language parameter set in request. If session support is enabled, the view saves the language choice in the user’s session. Otherwise, it saves the language choice in a cookie that is by default named django_language. (The name can be changed through the LANGUAGE_COOKIE_NAME setting.)

Tags:

Django