set_language(request)
[source]
As a convenience, Django comes with a view, django.views.i18n.set_language()
, that sets a user’s language preference and redirects to a given URL or, by default, back to the previous page.
Activate this view by adding the following line to your URLconf:
url(r'^i18n/', include('django.conf.urls.i18n')),
(Note that this example makes the view available at /i18n/setlang/
.)
Warning
Make sure that you don’t include the above URL within i18n_patterns()
- it needs to be language-independent itself to work correctly.
The view expects to be called via the POST
method, with a language
parameter set in request. If session support is enabled, the view saves the language choice in the user’s session. Otherwise, it saves the language choice in a cookie that is by default named django_language
. (The name can be changed through the LANGUAGE_COOKIE_NAME
setting.)
After setting the language choice, Django looks for a next
parameter in the POST
or GET
data. If that is found and Django considers it to be a safe URL (i.e. it doesn’t point to a different host and uses a safe scheme), a redirect to that URL will be performed. Otherwise, Django may fall back to redirecting the user to the URL from the Referer
header or, if it is not set, to /
, depending on the nature of the request:
- For AJAX requests, the fallback will be performed only if the
next
parameter was set. Otherwise a 204 status code (No Content) will be returned. - For non-AJAX requests, the fallback will always be performed.
Returning a 204 status code for AJAX requests when no redirect is specified is new.
Here’s example HTML template code:
{% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go" /> </form>
In this example, Django looks up the URL of the page to which the user will be redirected in the redirect_to
context variable.
Please login to continue.