Add Accept-Language fallback for first-visit redirect

This commit is contained in:
2026-05-11 23:53:11 +02:00
parent bbd9356517
commit 8a0c2849c0

View File

@@ -2,7 +2,10 @@ from __future__ import annotations
from django.conf import settings from django.conf import settings
from django.http import HttpRequest, HttpResponseRedirect from django.http import HttpRequest, HttpResponseRedirect
from django.utils.translation import get_language_from_request from django.utils.translation import (
get_language_from_request,
get_supported_language_variant,
)
class FirstVisitLanguageRedirectMiddleware: class FirstVisitLanguageRedirectMiddleware:
@@ -75,6 +78,22 @@ class FirstVisitLanguageRedirectMiddleware:
def _preferred_language(self, request: HttpRequest) -> str | None: def _preferred_language(self, request: HttpRequest) -> str | None:
matched = get_language_from_request(request, check_path=False) matched = get_language_from_request(request, check_path=False)
if not matched: if matched:
return None normalized = matched.split("-")[0].lower()
return matched.split("-")[0].lower() if normalized in self.supported_languages and normalized != self.default_language:
return normalized
# Fallback to raw Accept-Language parsing for unprefixed default routes.
header = request.META.get("HTTP_ACCEPT_LANGUAGE", "")
for item in header.split(","):
raw_lang = item.split(";", 1)[0].strip()
if not raw_lang:
continue
try:
variant = get_supported_language_variant(raw_lang)
except LookupError:
continue
normalized = variant.split("-")[0].lower()
if normalized in self.supported_languages:
return normalized
return None