"""Custom middleware.""" from django.utils import translation from configuration.models import TranslationSettings from translation.models import Language def get_locale(cookie_dict): return cookie_dict.get('locale') def get_country_code(cookie_dict): return cookie_dict.get('country_code') def parse_cookies(get_response): """Parse cookies.""" def middleware(request): cookie_dict = request.COOKIES # processing locale cookie locale = get_locale(cookie_dict) # todo: don't use DB!!! Use cache if not Language.objects.filter(locale=locale).exists(): locale = TranslationSettings.get_solo().default_language translation.activate(locale) request.locale = locale # processing country country cookie country_code = get_country_code(cookie_dict) request.country_code = country_code response = get_response(request) return response return middleware