Search code examples
djangodjango-templatesdjango-i18n

django languange change takes effect only after reload


In my app I can change the language by the following:

from django.utils.translation import LANGUAGE_SESSION_KEY
# LANGUAGE_SESSION_KEY is "_language"
...
def my_view(request, my_lang=en):
    request.session[LANGUAGE_SESSION_KEY] = my_lang
    ...
    context = {"mysession": session}
    return render(request, "mytemplate.html", context)

This works mostly as expected. However, the direct response of this view renders still in the previous language despite the session variable is set correctly. In other words the following template gives imho contradictory output:

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<b>Debug:</b>
current_language: {{ LANGUAGE_CODE }}
session_variable: {{mysession|get:"_language"}}

Note that, to access the attribute _language beginning with an underscore I have to use a custom filter, see this answer.

Django-Output:

Debug: current_language: en sessionvariable: de

All {% trans ... } statements are handled to the (outdated) content of LANGUAGE_CODE, which is annoying. After changing the language the uses expects an immediate effect. If I refresh the page or load a different view, then the new language is used correctly.

  1. Do I understand something wrong?
  2. How can I achieve that the current_language is set correctly in the immediate response.

Solution

  • You set the language code in the session, but you didn't actually activate the new language in the view.

    from django.utils import translation
    ...
    translation.activate(my_lang)