|
| 1 | +from django import http |
| 2 | +from django.conf import settings |
| 3 | +from django.core.urlresolvers import translate_url |
| 4 | +from django.utils.http import is_safe_url |
| 5 | +from django.utils.translation import LANGUAGE_SESSION_KEY, check_for_language |
| 6 | +from django.views.i18n import LANGUAGE_QUERY_PARAMETER |
| 7 | + |
| 8 | + |
| 9 | +# Modified from django.views.i18n |
| 10 | +def set_language(request): |
| 11 | + """ |
| 12 | + Redirect to a given url while setting the chosen language in the |
| 13 | + session or cookie. The url and the language code need to be |
| 14 | + specified in the request parameters. |
| 15 | + Since this view changes how the user will see the rest of the site, it must |
| 16 | + only be accessed as a POST request. If called as a GET request, it will |
| 17 | + redirect to the page in the request (the 'next' parameter) without changing |
| 18 | + any state. |
| 19 | + """ |
| 20 | + next = request.POST.get('next', request.GET.get('next')) |
| 21 | + if not is_safe_url(url=next, host=request.get_host()): |
| 22 | + next = request.META.get('HTTP_REFERER') |
| 23 | + if not is_safe_url(url=next, host=request.get_host()): |
| 24 | + next = '/' |
| 25 | + response = http.HttpResponseRedirect(next) |
| 26 | + if request.method == 'POST': |
| 27 | + lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) |
| 28 | + if lang_code and check_for_language(lang_code): |
| 29 | + next_trans = translate_url(next, lang_code) |
| 30 | + if next_trans != next: |
| 31 | + response = http.HttpResponseRedirect(next_trans) |
| 32 | + if hasattr(request, 'session'): |
| 33 | + request.session[LANGUAGE_SESSION_KEY] = lang_code |
| 34 | + # Always set cookie |
| 35 | + response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, |
| 36 | + max_age=settings.LANGUAGE_COOKIE_AGE, |
| 37 | + path=settings.LANGUAGE_COOKIE_PATH, |
| 38 | + domain=settings.LANGUAGE_COOKIE_DOMAIN) |
| 39 | + return response |
0 commit comments