Search code examples
pythondjangodjango-i18n

Django, change language while redirecting


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?


Solution

  • 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.