Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explicitly set django_language in django session

Tags:

How to explicitly set django_language in Django session?

Thanks a lot...

like image 864
icn Avatar asked Apr 09 '10 06:04

icn


2 Answers

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'
like image 26
Vladir Parrado Cruz Avatar answered Oct 01 '22 05:10

Vladir Parrado Cruz


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];
  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.

So 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'
    ...
like image 90
Anatoly Rr Avatar answered Oct 01 '22 05:10

Anatoly Rr