Skip to content

Instantly share code, notes, and snippets.

@alexissmirnov
Created June 15, 2011 20:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexissmirnov/1028020 to your computer and use it in GitHub Desktop.
Save alexissmirnov/1028020 to your computer and use it in GitHub Desktop.
Django QueryParameterLocaleMiddleware
from django.middleware import locale
from django.utils import translation
class QueryParameterLocaleMiddleware(locale.LocaleMiddleware):
"""
Django's LocaleMiddleware picks the locale setting of the request from
multiple sources such as a cookie, Accept-Language header and server-side
session.
This middleware adds one more way to specify the language by supplying
'locale' query parameter. It's value should be set to the same language
codes as required for Accept-Language.
Works with any HTTP verb (GET, POST, whatever)
"""
def process_request(self, request):
"""
Overrides the parent class to try getting the language code from
request parameter.
"""
if request.REQUEST.has_key('locale'):
translation.activate(request.REQUEST['locale'])
request.LANGUAGE_CODE = translation.get_language()
else:
super(QueryParameterLocaleMiddleware, self).process_request(request)
@alexissmirnov
Copy link
Author

Django's LocaleMiddleware picks the locale setting of the request from multiple sources such as a cookie, Accept-Language header and server-side session.
This middleware adds one more way to specify the language by supplying 'locale' query parameter. It's value should be set to the same language codes as required for Accept-Language.

Works with any HTTP verb (GET, POST, whatever)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment