Add Accept-Language fallback for first-visit redirect
This commit is contained in:
@@ -2,7 +2,10 @@ from __future__ import annotations
|
||||
|
||||
from django.conf import settings
|
||||
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:
|
||||
@@ -75,6 +78,22 @@ class FirstVisitLanguageRedirectMiddleware:
|
||||
|
||||
def _preferred_language(self, request: HttpRequest) -> str | None:
|
||||
matched = get_language_from_request(request, check_path=False)
|
||||
if not matched:
|
||||
if matched:
|
||||
normalized = 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
|
||||
return matched.split("-")[0].lower()
|
||||
|
||||
Reference in New Issue
Block a user