Search code examples
djangocookiesdjango-sessionsdjango-i18ndjango-1.9

Use cookie only for user language instead of opening session


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'

Solution

  • 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