0

I have set up my Django app to support various languages.

POST /i18n/setlang/ works and changes the language from the drop down menu.

<form action="/i18n/setlang/" method="post" class="form-inline">
    {% csrf_token %}
    <input name="next" type="hidden" value="/dashboard" />
    <select name="language" class="form-control" onchange="this.form.submit()">
        {% for lang in LANGUAGES %}
            <option value="{{ lang.0 }}" {% if request.LANGUAGE_CODE == lang.0 %} selected {% endif %}>{{ lang.1 }}</option>
        {% endfor %}
    </select>
</form>

In my database I know from the username the country of origin (usernames have been pre-asssigned). How can I automatically change the language and redirect to the first page, after login?

For example:

return HttpResponseRedirect(reverse("dashboard", args=[lang]))

or

return HttpResponseRedirect('/dashboard?lang=pt')

Is this possible without using any 3rd party middleware? If not, which middleware do you suggest?

ferrangb
  • 2,012
  • 2
  • 20
  • 34
xpanta
  • 8,124
  • 15
  • 60
  • 104

1 Answers1

4

You can change language explicitly after login like this:

from django.utils import translation
user_language = 'en'
translation.activate(user_language)
request.session['django_language'] = user_language

activate() will change the language for thread only, while changing the session makes it persistent in future requests.

inejc
  • 550
  • 3
  • 14
  • Thanks. I had to replace `request.session[translation.LANGUAGE_SESSION_KEY] = user_language` (because the project uses django 1.5.3) with `request.LANGUAGE_CODE = translation.get_language()` but it doesn't work. Any ideas what am I doing wrong? – xpanta Feb 24 '15 at 13:06
  • Is your language specified in settings.py? Also check out what is returned from translation.get_language() – inejc Feb 24 '15 at 13:35
  • yes and `get_language()` returns the `user_language` as it has been set previously. Both checked. – xpanta Feb 24 '15 at 14:04
  • Try to hardcode the language code and see if that works. You could also debug what is stored in the session as the language key. – inejc Feb 24 '15 at 14:19
  • Thanks. It now works. I just had to add this line, too: `request.session['django_language'] = user_language`. Please, update your answer, so I can mark it as correct for future readers that might have similar problems. – xpanta Feb 25 '15 at 09:11
  • Sorry if it is obvius, but where did you place it? – chopeds Jul 18 '17 at 09:51