import babel try: from threading import local except ImportError: from django.utils._threading_local import local _thread_locals = local() def get_current_locale(): """ Get current locale data outside views. See http://babel.edgewall.org/wiki/ApiDocs/babel.core for Locale objects documentation """ return getattr(_thread_locals, 'locale', None) class BabelMiddleware(object): """ This is a simple middleware that uses babel (http://babel.edgewall.org) for accessing locale data in request objects through request.LOCALE attribute """ def process_request(self, request): try: locale = babel.Locale.parse(request.LANGUAGE_CODE, sep='-') except (ValueError, babel.UnknownLocaleError): pass else: _thread_locals.locale = locale setattr(request, 'LOCALE', locale)