Site icon Tutorial

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:

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

Exit mobile version