The set_language Redirect View

As a convenience, Django comes with a view, django.views.i18n.set_language, that sets a user’s language preference and redirects back to the previous page. Activate this view by adding the following line to your URLconf:

(r’^i18n/’, include(‘django.conf.urls.i18n’)),

(Note that this example makes the view available at /i18n/setlang/.) The view expects to be called via the GET method, with a language parameter set in the query string. If session support is enabled, the view saves the language choice in the user’s session. Otherwise, it saves the language choice in a django_language cookie. After setting the language choice, Django redirects the user, following this algorithm:

  • Django looks for a next parameter in the query string.
  • If that doesn’t exist or is empty, Django tries the URL in the Referer header.
  • If that’s empty — say, if a user’s browser suppresses that header — then the user will be redirected to / (the site root) as a fallback.

Here’s example HTML template code:

<form action=”/i18n/setlang/” method=”get”>
<input name=”next” type=”hidden” value=”/next/page/” />
<select name=”language”>
{% for lang in LANGUAGES %}
<option value=”{{ lang.0 }}”>{{ lang.1 }}</option>
{% endfor %}
</select>
<input type=”submit” value=”Go” />
</form>

Back to Tutorial

How Django Discovers Language Preference
Using Translations in Your Own Projects

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?