Search code examples
djangodjango-authenticationdjango-i18n

Django: activate user-stored language after login


I'm using Python 3.6 and Django 1.11. I'm using Django class-based auth views and custom user model. My users have their language stored in database. I would like to retrieve this language after every login and activate it.

I was hoping to do this through user_logged_in signal, but signals cannot affect response in any way, so this is not possible.

Another way is to override default auth views, which is something I wanted to avoid.

Is there any other way? Thank you.


Solution

  • In the end, I went with a minimal auth view override. I found this better than custom language middleware, because middleware would add some overhead to every request, whereas this is executed only during login. I have overridden the get_success_url method because it is being called after user is logged in (that I need) and I didn't want to interfere with the login/authentication process itself, because that could potentially introduce a security hole in the future.

    from django.conf import settings
    from django.contrib.auth.views import LoginView
    from django.urls import translate_url
    from django.utils.translation import activate, LANGUAGE_SESSION_KEY
    
    # available languages should be obtained from settings.LANGUAGES
    available_languages = [lang_code for (lang_code, lang_name) in settings.LANGUAGES]
    
    class CustomLoginView(LoginView):
        def get_success_url(self):
            url = super(CustomLoginView, self).get_success_url()
            user = self.request.user
            if user.is_authenticated():
                language = user.get_setting('language')
    
                if language in available_languages:
                    url = translate_url(url, language)
                    activate(language)
                    if hasattr(self.request, 'session'):
                        self.request.session[LANGUAGE_SESSION_KEY] = language
    
            return url