Login

Set language via HTTP GET Parameter

Author:
schmidsi
Posted:
March 2, 2010
Language:
Python
Version:
1.1
Tags:
get session http language translation
Score:
2 (after 2 ratings)

Two middlewares to handle languages via HTTP GET

original code by stefan reinhard, check against django.conf.settings by me

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from django.conf import settings

from django.utils.cache import patch_vary_headers
from django.utils import translation

class SessionBasedLocaleMiddleware(object):
    """
    This Middleware saves the desired content language in the user session.
    The SessionMiddleware has to be activated.
    """
    def process_request(self, request):
        if request.method == 'GET' and 'lang' in request.GET:
                language = request.GET['lang']
                request.session['language'] = language
        elif 'language' in request.session:
                language = request.session['language']
        else:
                language = translation.get_language_from_request(request)
        
        for lang in settings.LANGUAGES:
            if lang[0] == language:
                translation.activate(language)
                
        request.LANGUAGE_CODE = translation.get_language()

    def process_response(self, request, response):
        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response

More like this

  1. Ignore HTTP Accept-Language headers by fonso 8 years, 2 months ago
  2. I18n Get all language models with form. Tüm diller için otomatik form by muslu 3 years, 1 month ago
  3. LocaleMiddleware without browser language discovery by ivellios 5 months ago
  4. Get active page's url by another language (templatetag) by muratcorlu 2 years, 6 months ago
  5. I18n URLs via Middleware by zerok 7 years, 11 months ago

Comments

chronos (on July 23, 2010):

I need to talk, this one is perfect. I sugest that you send it as one improvement to Django project, have a lot of people wanting for this :)

#

jose_lpa (on October 16, 2013):

Thanks for this one!

#

Please login first before commenting.