Features: 1) Add CustomLocaleMiddleware for language normalization and activation.

Fixes: None;

Extra: 1) Add CustomLocaleMiddleware to middleware stack in base settings; 2) Add missing import for LocaleMiddleware and translation module; 3) Refactor locale handling by extending LocaleMiddleware.
This commit is contained in:
Egor Pavlovich Gorbunov 2025-05-20 21:39:07 +03:00
parent 9d7efa310a
commit 123459ede5
2 changed files with 18 additions and 0 deletions

View file

@ -7,7 +7,9 @@ from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import DisallowedHost
from django.http import HttpResponseForbidden
from django.middleware.common import CommonMiddleware
from django.middleware.locale import LocaleMiddleware
from django.shortcuts import redirect
from django.utils import translation
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken
from sentry_sdk import capture_exception
@ -23,6 +25,21 @@ class CustomCommonMiddleware(CommonMiddleware):
return redirect(f"https://api.{config.BASE_DOMAIN}")
class CustomLocaleMiddleware(LocaleMiddleware):
def process_request(self, request):
lang = translation.get_language_from_request(request)
parts = lang.replace('_', '-').split('-')
if len(parts) == 2:
lang_code = parts[0].lower()
region = parts[1].upper()
normalized = f"{lang_code}-{region}"
else:
normalized = lang
translation.activate(normalized)
request.LANGUAGE_CODE = normalized
class GrapheneJWTAuthorizationMiddleware:
def resolve(self, next, root, info, **args):
context = info.context

View file

@ -108,6 +108,7 @@ MIDDLEWARE = [
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.middleware.locale.LocaleMiddleware",
"evibes.middleware.CustomLocaleMiddleware",
"django_hosts.middleware.HostsResponseMiddleware",
"djangorestframework_camel_case.middleware.CamelCaseMiddleWare",
]