How to set the language for the whole session after login in Django

Viewed 273

I'm stuck, trying to set the language for an entire session, so that the menus, forms, etc. are displayed according to the language entered during login.

For this I have defined the following:

In the settings.py file add the middleware:

'django.middleware.locale.LocaleMiddleware',

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Also add the context renderer: 'django.template.context_processors.i18n'

And I defined my 3 languages:

LANGUAGE_CODE = 'es'

LANGUAGES = [
    ('es' _('Spanish')),
    ('en', _ ('English')),
    ('it', _ ('Italian')),
] 

This is my view:

class LoginFormView(FormView):
    form_class = UserLoginForm
    template_name = 'login.html'
    success_url = reverse_lazy('index')

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(self.success_url)
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        login(self.request, form.get_user())
        user_language = self.request.POST.get('language', None)
        translation.activate(user_language)
        self.request.session['django_language'] = user_language
        self.request.session[translation.LANGUAGE_SESSION_KEY] = user_language
        return HttpResponseRedirect(self.success_url)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Iniciar sesión'
        return context

Despite this, the language after login does not change and always remains in Spanish.

All templates have the tag:

{% load i18n %}

I also tried to force the language change by placing a button in the navigation bar, in order to test if the translation works and is indeed working well:

<button type="button" class="btn-shadow p-1 btn btn-primary btn-sm">
  {% include 'change_language.html' %}
  <i class="fa text-white fa-calendar pr-1 pl-1"></i>
</button>

change_language.html

 {% load i18n %}
    <form action="/i18n/setlang/" method="post" style="display: inline;">
    {% csrf_token %}
      <div style="display: inline;">
        <select name="language" onchange="javascript:form.submit()">
          {% for lang in LANGUAGES %}
            <option value="{{ lang.0 }}"{% ifequal LANGUAGE_CODE lang.0 %} selected="selected"{% endifequal %}>{{ lang.1 }}</option>
          {% endfor %}
        </select>
      </div>
    </form>

Therefore, I do not know if the code that I am putting in the form_valid() is correct and if it should go there.

0 Answers
Related