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

Comments

chronos (on July 23, 2010):
<p>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 :)</p>

#

jose_lpa (on October 16, 2013):
<p>Thanks for this one!</p>

#

Please login first before commenting.