Create a new middleware
from django.utils.translation import activate
from django.conf import settings
<pre>
class CustomLanguageMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Read the language preference from the local storage cookie
language_preference = request.COOKIES.get('language_preference', None) # Instead of `None` set your default language code in case of there is no language_preference comes with cookies
# If a language preference is found, set the 'Accept-Language' header
if language_preference and language_preference in dict(settings.LANGUAGES):
request.META['HTTP_ACCEPT_LANGUAGE'] = language_preference
# Call the next middleware or view
response = self.get_response(request)
# If you want, you can also update the 'language' in the session
if language_preference and language_preference in dict(settings.LANGUAGES):
activate(language_preference)
return response
</pre>
add it right before `django.middleware.locale.LocaleMiddleware`
DJANGO_MIDDLEWARES = [
# add your custom middleware here
'django.middleware.locale.LocaleMiddleware',
]
this custom middleware will override the default behavior of the LocalMiddleware.
Finally, you can store the language preference in the local storage cookie:
<pre>
const languagePreference = 'ru-RU'; // Replace this with the user's preferred language
localStorage.setItem('language_preference', languagePreference);
</pre>