[docs]classLocaleMiddleware(MiddlewareMixin):""" Parse a request and decide what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is available, of course). """response_redirect_class=HttpResponseRedirectdefprocess_request(self,request):urlconf=getattr(request,'urlconf',settings.ROOT_URLCONF)i18n_patterns_used,prefixed_default_language=is_language_prefix_patterns_used(urlconf)language=translation.get_language_from_request(request,check_path=i18n_patterns_used)language_from_path=translation.get_language_from_path(request.path_info)ifnotlanguage_from_pathandi18n_patterns_usedandnotprefixed_default_language:language=settings.LANGUAGE_CODEtranslation.activate(language)request.LANGUAGE_CODE=translation.get_language()defprocess_response(self,request,response):language=translation.get_language()language_from_path=translation.get_language_from_path(request.path_info)urlconf=getattr(request,'urlconf',settings.ROOT_URLCONF)i18n_patterns_used,prefixed_default_language=is_language_prefix_patterns_used(urlconf)if(response.status_code==404andnotlanguage_from_pathandi18n_patterns_usedandprefixed_default_language):# Maybe the language code is missing in the URL? Try adding the# language prefix and redirecting to that URL.language_path='/%s%s'%(language,request.path_info)path_valid=is_valid_path(language_path,urlconf)path_needs_slash=(notpath_validand(settings.APPEND_SLASHandnotlanguage_path.endswith('/')andis_valid_path('%s/'%language_path,urlconf)))ifpath_validorpath_needs_slash:script_prefix=get_script_prefix()# Insert language after the script prefix and before the# rest of the URLlanguage_url=request.get_full_path(force_append_slash=path_needs_slash).replace(script_prefix,'%s%s/'%(script_prefix,language),1)returnself.response_redirect_class(language_url)ifnot(i18n_patterns_usedandlanguage_from_path):patch_vary_headers(response,('Accept-Language',))response.setdefault('Content-Language',language)returnresponse