Issue with language translation not applying fully in Django with token-based authentication

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:

  1. I have set up multiple languages in settings.py (LANGUAGES) and configured the default language to be English (LANGUAGE_CODE = 'en').
  2. I am using token-based authentication (rest_framework.authtoken) to authenticate users. The user’s preferred language is stored in the database as preferred_language.
  3. 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:

  1. When I check the active language in the view using get_language(), it correctly reflects the preferred language for the session.
  2. I have verified that the preferred language is correctly set in both the session and cookie (cookie_language_tinocoloco).
  3. The LocaleMiddleware is configured to activate the language, but it’s not applying to dynamic messages.

What I have tried:

  1. I have ensured that the middleware order is correct. The SessionMiddleware is before LocaleMiddleware, and LocaleMiddleware is before AuthenticationMiddleware, which is consistent with the recommended setup.
  2. 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