Django language switcher is not persistent

11 Views Asked by At

Hello I'm struggling with my language switcher.

settings.py:

LANGUAGE_CODE = 'en'
LANGUAGES = [
    ('de','Deutsch'),
    ('en','English')
]

urls.py:

path('setlang', views.setlang, name='setlang'),

index.html:

<a href="{% url 'setlang' %}">{% trans "English" %}</a>

views.py

def setlang(request):
    logger.error(get_language())
    if get_language() == 'de':
        activate('en')
    else:
        activate('de')
    logger.error(get_language())
    return redirect('index')

Output from logger.error(get_language()) -> 'de' than 'en'.

It's everytime 'de'! Even if I set LANGUAGE_CODE = 'en'! I've no idea where the 'de' is coming from.

The problem is maybe the reload, which is forced by the return redirect('index')?

Translation in general works.

Has anyone an idea how I can stick to the language which is selected and not fall back to default?

1

There are 1 best solutions below

0
willeM_ Van Onsem On BEST ANSWER

activate(…) [Django-doc] is not supposed to be persistent. Indeed, as the documentation says:

Fetches the translation object for a given language and activates it as the current translation object for the current thread.

It thus "dies" after the the thread is finished.

You can set the cookie of the LANGUAGE_COOKIE_NAME setting [Django-doc] to activate a different language:

from django.conf import settings


def setlang(request):
    logger.error(get_language())
    if get_language() == 'de':
        lang = 'en'
    else:
        lang = 'de'
    response = redirect('index')
    response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang)
    return response