I am working on a Django application that supports multiple languages. I am using token-based authentication and trying to change the language for authenticated users based on their preference stored in their profile. However, I am encountering a few issues regarding how the translations are being applied, particularly when it comes to dynamic message translations.
What I have:
- I have set up multiple languages in
settings.py
(LANGUAGES
) and configured the default language to be English (LANGUAGE_CODE = 'en'
). - I am using token-based authentication (
rest_framework.authtoken
) to authenticate users. The user’s preferred language is stored in the database aspreferred_language
. - I have added a custom middleware to handle language switching based on the user’s preference, which should be applied as soon as the user is authenticated and the session is set
Problem:
- Language preference seems to be applied for static content (like templates), but dynamic translations for strings in views (using
gettext
) are not applying correctly after the user’s preferred language is set. - For example, while the language change works partially (like UI content), messages generated using
gettext()
(like error or success messages) are still showing in the default language (en
), not the user’s preferred language (e.g.,es
for Spanish).
Here are some observations:
- When I check the active language in the view using
get_language()
, it correctly reflects the preferred language for the session. - I have verified that the preferred language is correctly set in both the session and cookie (
cookie_language_tinocoloco
). - The
LocaleMiddleware
is configured to activate the language, but it’s not applying to dynamic messages.
What I have tried:
- I have ensured that the middleware order is correct. The
SessionMiddleware
is beforeLocaleMiddleware
, andLocaleMiddleware
is beforeAuthenticationMiddleware
, which is consistent with the recommended setup. - I have manually activated the language in the middleware using
translation.activate(user.preferred_language)
.
from django.utils import translation
def get_user_language(user):
if user and hasattr(user, 'preferred_language') and user.preferred_language:
return user.preferred_language
return None
class LanguageMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if hasattr(request, 'user') and request.user.is_authenticated:
language = get_user_language(request.user)
if language:
translation.activate(language) # Activate user preferred language
response = self.get_response(request)
return response