fix(i18n): normalize setlang next path server-side
This commit is contained in:
31
mandelstudio/i18n_utils.py
Normal file
31
mandelstudio/i18n_utils.py
Normal 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, ""))
|
||||
Reference in New Issue
Block a user