Search code examples
djangodjango-modelslocalizationinternationalization

Django localization use language from user model


I'm trying to take user language from UserProfile model. User choosing language in form, and after that website have to be translated on that language. I created switcher which can change language but it's not what i need because it doesn't communicate with my model. I know that i have to rewrite LocaleMiddleware, but i don't know how to do it in right way. I've tried some solution from stackoverflow, but it doesn't work for me.

So the question is: what i'm doing wrong? or maybe there is no problem with middleware but problem somewhere else?

My middleware:

from django.utils import translation


class LocaleMiddleware(object):
    """
    This is a very simple middleware that parses a request
    and decides what translation object to install in the current
    thread context. This allows pages to be dynamically
    translated to the language the user desires (if the language
    is available, of course).
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        language_code = request.LANGUAGE_CODE
        translation.activate(language_code)
        response = self.get_response(request)
        translation.deactivate()
        return response

    def process_request(self, request):
        language = translation.get_language_from_request(request)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

    def process_response(self, request, response):
        translation.deactivate()
        return response

My model:

from core.settings.base import LANGUAGES, LANGUAGE_CODE


class UserProfile(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, related_name="user_profile"
    )
    phone_number = models.CharField(
        max_length=16,
        blank=True,
        null=True,
        validators=[
            RegexValidator(
                regex=r"^\+?1?\d{9,15}$",
                message="Phone number must be entered in the format '+123456789'. Up to 15 digits allowed.",
            ),
        ],
    )
    language = models.CharField(
        choices=LANGUAGES, default=LANGUAGE_CODE, max_length=10
    )

    objects = models.Manager()

Solution

  • Finally i found an answer.

    from django.utils import translation
    from django.utils.deprecation import MiddlewareMixin
    
    
    class CustomLocaleMiddleware(MiddlewareMixin):
        def process_request(self, request):
            try:
                if request.user.is_authenticated:
                    translation.activate(request.user.user_profile.language)
                    request.LANGUAGE_CODE = request.user.user_profile.language
            except:
                request.LANGUAGE_CODE = "en"