2

I have set number of languages and translations on my site, they work fine. Added language switch control on my page.

Switch language cause setting session token for every [anonymous] user. How can i avoid this and use only cookie for localization? I mean do not use session, but use something like "{language:'en'}" in cookies, handled automatically?

settings.py config has these settings alongside with locale paths and etc.:

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

LANGUAGE_COOKIE_NAME = 'language'
Croll
  • 3,631
  • 6
  • 30
  • 63

2 Answers2

3

You can do that by writing your own middleware that will:

  • Create a language cookie if it does not exist already.

  • Set the language according to the cookie.

So you can write something like that:

from django.utils import translation


class LanguageCookieMiddleware():

    def process_request(self, request):
        """
        Sets language from the cookie value.
        """
        if request.COOKIES.has_key(COOKIE_NAME):
            language = request.COOKIES.get(COOKIE_NAME)
            # You should add here some code to check teh language
            # variable is safe...
            translation.activate(language)
            request.LANGUAGE_CODE = translation.get_language()

    def process_response(self, request, response):
        """
        Create cookie if not there already.

        Also deactivates language.
        (See http://stackoverflow.com/a/13031239/388835 )
        """

        if not request.COOKIES.has_key(COOKIE_NAME):
            response.set_cookie(HTTP_COOKIE_NAME,
                                function_for_language_code_you_want())
        translation.deactivate()
        return response
Nayan
  • 1,521
  • 2
  • 13
  • 27
mimo
  • 2,469
  • 2
  • 28
  • 49
1

I wouldn't recommend directly storing the data in the cookie.

  • It takes up a place in the browser cache of the client.
  • More importantly, you're doing something dangerous. Now the data lives on the client's browser instead of your database. You may see the language data not important, but there are more to take advantage of.

If you're complaining about the large number of session keys, you should delete the session key some time later (maybe at browser close?). It's up to you.

K.Yazoglu
  • 207
  • 3
  • 13