Login

Set language via HTTP GET Parameter

Author:
schmidsi
Posted:
March 2, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.