fix(i18n): normalize setlang next path server-side

This commit is contained in:
2026-04-10 23:03:15 +02:00
parent 944e88d78d
commit 58139b08ff
5 changed files with 124 additions and 23 deletions

View File

@@ -0,0 +1,31 @@
from __future__ import annotations
import re
from urllib.parse import urlsplit, urlunsplit
from django.conf import settings
def normalize_set_language_next(value: str | None) -> str:
"""
Normalize the `next` path used by Django's set_language view.
Removes any leading language prefix from the path so switching from one
locale to another cannot produce duplicated prefixes like `/de/en/...`.
"""
if not value:
return "/"
parsed = urlsplit(str(value))
path = parsed.path or "/"
if not path.startswith("/"):
path = f"/{path}"
language_codes = [code for code, _ in settings.LANGUAGES]
if language_codes:
pattern = (
rf"^/(?:{'|'.join(re.escape(code) for code in language_codes)})(?=/|$)"
)
path = re.sub(pattern, "", path, count=1) or "/"
return urlunsplit(("", "", path, parsed.query, ""))