EN VI

Python - Django language switcher is not persistent?

2024-03-14 04:30:04
Python - Django language switcher is not persistent

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?

Solution:

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
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login