Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: change app language programmatically (without /i18n/setlang/ view)

My situation is the following:

I'm developing a multi-language site and currently I use the Django view /i18n/setlang/ to let user switch language from a dropdown menu, and all works fine… but now, I wish to set the language programmatically, specifically I have a form with a series of settings and, among these, there is a "favorite language" voice, once the user submit the form, my view saves the User model and theoretically after that it should set the application language using the saved preference, but it does not work. What I tried is:

from django.utils.translation import activate

activate(lang)

but the result is bizarre: the UI after the redirect is still in the old language, but the message of successful update (django messages framework) is displayed back in the expected language!

I've also checked the source code of the Django view: https://github.com/django/django/blob/master/django/views/i18n.py

And I saw that they save the selected language in session if available (I have session activated), so I tried:

self.request.session['_language'] = form.cleaned_data['favouriteLanguage']

…but is not working, what should I do?

I'm using Django 1.6 and the django middleware I did install are the following:

    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',

ps: in both my tries, {{ request.LANGUAGE_CODE }} in template prints the old language code :(

like image 263
daveoncode Avatar asked Sep 17 '25 20:09

daveoncode


1 Answers

activate alone does not do the trick.

Check out django.views.i18n.set_language:

def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.REQUEST.get('next')
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    return response

It has everything you need to do to set language in view programmatically. since you already have localemiddleware, then that view is all you need. But do not copy paste it just like that. Keep that activate in that view. I think you might need that one though :)

like image 94
Odif Yltsaeb Avatar answered Sep 21 '25 04:09

Odif Yltsaeb