Python django.conf.settings.LANGUAGE_COOKIE_NAME Examples

The following are 30 code examples for showing how to use django.conf.settings.LANGUAGE_COOKIE_NAME(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
def set_user_language(request):
    next = request.REQUEST.get('next')
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if 'ref' not in next:
            ref = urlparse(request.POST.get('referrer', next))
            response = HttpResponseRedirect('?ref='.join([next, ref.path]))
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)

        user = request.user
        if user.is_authenticated():
            user_profile = user.profile
            user_profile.language = lang_code
            user_profile.save()
    return response 
Example 2
Project: luscan-devel   Author: blackye   File: i18n.py    License: GNU General Public License v2.0 6 votes vote down vote up
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.REQUEST.get('next')
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    return response 
Example 3
Project: django-userena-ce   Author: django-userena-ce   File: middleware.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_request(self, request):
        lang_cookie = request.session.get(settings.LANGUAGE_COOKIE_NAME)
        if not lang_cookie:

            authenticated = request.user.is_authenticated

            if authenticated:
                try:
                    profile = get_user_profile(user=request.user)
                except (ObjectDoesNotExist, SiteProfileNotAvailable):
                    profile = False

                if profile:
                    try:
                        lang = getattr(profile, userena_settings.USERENA_LANGUAGE_FIELD)
                        translation.activate(lang)
                        request.LANGUAGE_CODE = translation.get_language()
                    except AttributeError:
                        pass 
Example 4
Project: djongo   Author: nesdis   File: test_i18n.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_setlang(self):
        """
        The set_language view can be used to change the session language.

        The user is redirected to the 'next' argument if provided.
        """
        lang_code = self._get_inactive_language_code()
        post_data = {'language': lang_code, 'next': '/'}
        response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i_should_not_be_used/')
        self.assertRedirects(response, '/')
        self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
        # The language is set in a cookie.
        language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME]
        self.assertEqual(language_cookie.value, lang_code)
        self.assertEqual(language_cookie['domain'], '')
        self.assertEqual(language_cookie['path'], '/')
        self.assertEqual(language_cookie['max-age'], '') 
Example 5
Project: djongo   Author: nesdis   File: test_i18n.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_setlang_cookie(self):
        # we force saving language to a cookie rather than a session
        # by excluding session middleware and those which do require it
        test_settings = {
            'MIDDLEWARE': ['django.middleware.common.CommonMiddleware'],
            'LANGUAGE_COOKIE_NAME': 'mylanguage',
            'LANGUAGE_COOKIE_AGE': 3600 * 7 * 2,
            'LANGUAGE_COOKIE_DOMAIN': '.example.com',
            'LANGUAGE_COOKIE_PATH': '/test/',
        }
        with self.settings(**test_settings):
            post_data = {'language': 'pl', 'next': '/views/'}
            response = self.client.post('/i18n/setlang/', data=post_data)
            language_cookie = response.cookies.get('mylanguage')
            self.assertEqual(language_cookie.value, 'pl')
            self.assertEqual(language_cookie['domain'], '.example.com')
            self.assertEqual(language_cookie['path'], '/test/')
            self.assertEqual(language_cookie['max-age'], 3600 * 7 * 2) 
Example 6
Project: djongo   Author: nesdis   File: test_i18n.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_setlang(self):
        """
        The set_language view can be used to change the session language.

        The user is redirected to the 'next' argument if provided.
        """
        lang_code = self._get_inactive_language_code()
        post_data = {'language': lang_code, 'next': '/'}
        response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i_should_not_be_used/')
        self.assertRedirects(response, '/')
        self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code)
        # The language is set in a cookie.
        language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME]
        self.assertEqual(language_cookie.value, lang_code)
        self.assertEqual(language_cookie['domain'], '')
        self.assertEqual(language_cookie['path'], '/')
        self.assertEqual(language_cookie['max-age'], '') 
Example 7
Project: djongo   Author: nesdis   File: test_i18n.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_setlang_cookie(self):
        # we force saving language to a cookie rather than a session
        # by excluding session middleware and those which do require it
        test_settings = {
            'MIDDLEWARE': ['django.middleware.common.CommonMiddleware'],
            'LANGUAGE_COOKIE_NAME': 'mylanguage',
            'LANGUAGE_COOKIE_AGE': 3600 * 7 * 2,
            'LANGUAGE_COOKIE_DOMAIN': '.example.com',
            'LANGUAGE_COOKIE_PATH': '/test/',
        }
        with self.settings(**test_settings):
            post_data = {'language': 'pl', 'next': '/views/'}
            response = self.client.post('/i18n/setlang/', data=post_data)
            language_cookie = response.cookies.get('mylanguage')
            self.assertEqual(language_cookie.value, 'pl')
            self.assertEqual(language_cookie['domain'], '.example.com')
            self.assertEqual(language_cookie['path'], '/test/')
            self.assertEqual(language_cookie['max-age'], 3600 * 7 * 2) 
Example 8
Project: esdc-ce   Author: erigones   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def setlang(request):
    """
    Sets a user's language preference and redirects to a given URL or, by default, back to the previous page.
    """
    next = request.GET.get('next', None)
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = redirect(next)

    lang_code = request.GET.get('language', None)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session[LANGUAGE_SESSION_KEY] = lang_code
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                max_age=settings.LANGUAGE_COOKIE_AGE,
                                path=settings.LANGUAGE_COOKIE_PATH,
                                domain=settings.LANGUAGE_COOKIE_DOMAIN)

    return response 
Example 9
Project: avos   Author: CiscoSystems   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
def handle(self, request, data):
        response = shortcuts.redirect(request.build_absolute_uri())
        # Language
        lang_code = data['language']
        if lang_code and translation.check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                expires=_one_year())

        # Timezone
        request.session['django_timezone'] = pytz.timezone(
            data['timezone']).zone
        response.set_cookie('django_timezone', data['timezone'],
                            expires=_one_year())

        request.session['horizon_pagesize'] = data['pagesize']
        response.set_cookie('horizon_pagesize', data['pagesize'],
                            expires=_one_year())

        with translation.override(lang_code):
            messages.success(request,
                             encoding.force_text(_("Settings saved.")))

        return response 
Example 10
Project: astrobin   Author: astrobin   File: __init__.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def user_profile_save_preferences(request):
    """Saves the form"""

    profile = request.user.userprofile
    form = UserProfileEditPreferencesForm(data=request.POST, instance=profile)
    response_dict = {'form': form}
    response = HttpResponseRedirect("/profile/edit/preferences/")

    if form.is_valid():
        form.save()
        # Activate the chosen language
        from django.utils.translation import check_for_language, activate
        lang = form.cleaned_data['language']
        if lang and check_for_language(lang):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang

            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang)
            activate(lang)
    else:
        return render(request, "user/profile/edit/preferences.html", response_dict)

    messages.success(request, _("Form saved. Thank you!"))
    return response 
Example 11
Project: astrobin   Author: astrobin   File: __init__.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def set_language(request, lang):
    from django.utils.translation import check_for_language, activate

    next = request.GET.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = HttpResponseRedirect(next)
    if lang and check_for_language(lang):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang

        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang)
        activate(lang)

    if request.user.is_authenticated():
        profile = request.user.userprofile
        profile.language = lang
        profile.save(keep_deleted=True)

    return response 
Example 12
Project: GTDWeb   Author: lanbing510   File: i18n.py    License: GNU General Public License v2.0 5 votes vote down vote up
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                    max_age=settings.LANGUAGE_COOKIE_AGE,
                                    path=settings.LANGUAGE_COOKIE_PATH,
                                    domain=settings.LANGUAGE_COOKIE_DOMAIN)
    return response 
Example 13
Project: bioforum   Author: reBiocoder   File: i18n.py    License: MIT License 5 votes vote down vote up
def set_language(request):
    """
    Redirect to a given URL while setting the chosen language in the session or
    cookie. The URL and the language code need to be specified in the request
    parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if ((next or not request.is_ajax()) and
            not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())):
        next = request.META.get('HTTP_REFERER')
        if next:
            next = unquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
            next = '/'
    response = HttpResponseRedirect(next) if next else HttpResponse(status=204)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            if next:
                next_trans = translate_url(next, lang_code)
                if next_trans != next:
                    response = HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(
                    settings.LANGUAGE_COOKIE_NAME, lang_code,
                    max_age=settings.LANGUAGE_COOKIE_AGE,
                    path=settings.LANGUAGE_COOKIE_PATH,
                    domain=settings.LANGUAGE_COOKIE_DOMAIN,
                )
    return response 
Example 14
Project: dissemin   Author: dissemin   File: conftest.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def check_page(request, dissemin_base_client, validator_tools):
    """
    Checks status of page and checks html. 
    """
    def checker(status, *args, **kwargs):
        vt = validator_tools
        vt.client = kwargs.pop('client', dissemin_base_client)
        vt.client.cookies.load({settings.LANGUAGE_COOKIE_NAME : request.param})
        vt.check_page(status, *args, **kwargs)

    return checker 
Example 15
Project: dissemin   Author: dissemin   File: conftest.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def check_url(request, validator_tools):
    """
    Checks status and html of a URL
    """

    def checker(status, url):
        vt = validator_tools
        vt.client.cookies.load({settings.LANGUAGE_COOKIE_NAME : request.param})
        vt.check_url(status, url)

    return checker 
Example 16
Project: zulip   Author: zulip   File: test_i18n.py    License: Apache License 2.0 5 votes vote down vote up
def test_cookie(self) -> None:
        languages = [('en', 'Sign up'),
                     ('de', 'Registrieren'),
                     ('sr', 'Упишите се'),
                     ('zh-hans', '注册'),
                     ]

        for lang, word in languages:
            # Applying str function to LANGUAGE_COOKIE_NAME to convert unicode
            # into an ascii otherwise SimpleCookie will raise an exception
            self.client.cookies = SimpleCookie({str(settings.LANGUAGE_COOKIE_NAME): lang})

            response = self.fetch('get', '/integrations/', 200)
            self.assert_in_response(word, response) 
Example 17
Project: zing   Author: evernote   File: override.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_lang_from_cookie(request, supported):
    """See if the user's browser sent a cookie with a preferred language."""
    from django.conf import settings

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)

    if lang_code and lang_code in supported:
        return lang_code

    return None 
Example 18
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: i18n.py    License: MIT License 5 votes vote down vote up
def set_language(request):
    """
    Redirect to a given URL while setting the chosen language in the session
    (if enabled) and in a cookie. The URL and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if ((next or not request.is_ajax()) and
            not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())):
        next = request.META.get('HTTP_REFERER')
        next = next and unquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
            next = '/'
    response = HttpResponseRedirect(next) if next else HttpResponse(status=204)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            if next:
                next_trans = translate_url(next, lang_code)
                if next_trans != next:
                    response = HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            response.set_cookie(
                settings.LANGUAGE_COOKIE_NAME, lang_code,
                max_age=settings.LANGUAGE_COOKIE_AGE,
                path=settings.LANGUAGE_COOKIE_PATH,
                domain=settings.LANGUAGE_COOKIE_DOMAIN,
            )
    return response 
Example 19
Project: python   Author: Yeah-Kun   File: i18n.py    License: Apache License 2.0 5 votes vote down vote up
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if ((next or not request.is_ajax()) and
            not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())):
        next = request.META.get('HTTP_REFERER')
        if next:
            next = urlunquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
            next = '/'
    response = http.HttpResponseRedirect(next) if next else http.HttpResponse(status=204)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            if next:
                next_trans = translate_url(next, lang_code)
                if next_trans != next:
                    response = http.HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(
                    settings.LANGUAGE_COOKIE_NAME, lang_code,
                    max_age=settings.LANGUAGE_COOKIE_AGE,
                    path=settings.LANGUAGE_COOKIE_PATH,
                    domain=settings.LANGUAGE_COOKIE_DOMAIN,
                )
    return response 
Example 20
Project: openhgsenti   Author: drexly   File: i18n.py    License: Apache License 2.0 5 votes vote down vote up
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            next_trans = translate_url(next, lang_code)
            if next_trans != next:
                response = http.HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                    max_age=settings.LANGUAGE_COOKIE_AGE,
                                    path=settings.LANGUAGE_COOKIE_PATH,
                                    domain=settings.LANGUAGE_COOKIE_DOMAIN)
    return response 
Example 21
Project: python2017   Author: bpgc-cte   File: i18n.py    License: MIT License 5 votes vote down vote up
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if ((next or not request.is_ajax()) and
            not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure())):
        next = request.META.get('HTTP_REFERER')
        if next:
            next = urlunquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(url=next, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
            next = '/'
    response = http.HttpResponseRedirect(next) if next else http.HttpResponse(status=204)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            if next:
                next_trans = translate_url(next, lang_code)
                if next_trans != next:
                    response = http.HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(
                    settings.LANGUAGE_COOKIE_NAME, lang_code,
                    max_age=settings.LANGUAGE_COOKIE_AGE,
                    path=settings.LANGUAGE_COOKIE_PATH,
                    domain=settings.LANGUAGE_COOKIE_DOMAIN,
                )
    return response 
Example 22
Project: ecommerce   Author: edx   File: test_paypal.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_resolve_paypal_locale(self, default_locale, cookie_locale, expected_paypal_locale, mock_method):
        """
        Verify that the correct locale for payment processing is fetched from the language cookie
        """
        translation.activate(default_locale)
        mock_method.side_effect = Exception("End of test")  # Force test to end after this call

        toggle_switch('create_and_set_webprofile', True)
        self.request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = cookie_locale
        try:
            self.processor.get_transaction_parameters(self.basket, request=self.request)
        except Exception:  # pylint: disable=broad-except
            pass
        mock_method.assert_called_with(expected_paypal_locale) 
Example 23
Project: ecommerce   Author: edx   File: test_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_order_value_unlocalized_for_tracking(self, mock_learner_data):
        mock_learner_data.return_value = self.non_enterprise_learner_data
        order = self._create_order_for_receipt(self.user)
        self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: 'fr'})
        response = self._get_receipt_response(order.number)

        self.assertEqual(response.status_code, 200)
        order_value_string = 'data-total-amount="{}"'.format(order.total_incl_tax)
        self.assertContains(response, order_value_string) 
Example 24
Project: pyconkr-2014   Author: pythonkr   File: views.py    License: MIT License 5 votes vote down vote up
def setlang(request, lang_code):
    # Copied from django.views.i18n.set_language
    next = request.REQUEST.get('next')
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = HttpResponseRedirect(next)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang_code
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    return response 
Example 25
Project: TWLight   Author: WikipediaLibrary   File: views.py    License: MIT License 5 votes vote down vote up
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get("next", request.GET.get("next"))
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get("HTTP_REFERER")
        if not is_safe_url(url=next, host=request.get_host()):
            next = "/"
    response = http.HttpResponseRedirect(next)
    if request.method == "POST":
        lang_code = request.POST.get("language", None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, "session"):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(
                    settings.LANGUAGE_COOKIE_NAME,
                    lang_code,
                    max_age=settings.LANGUAGE_COOKIE_AGE,
                    path=settings.LANGUAGE_COOKIE_PATH,
                    domain=settings.LANGUAGE_COOKIE_DOMAIN,
                )
            if request.user.is_authenticated():
                request.user.userprofile.lang = lang_code
                request.user.userprofile.save()
    return response 
Example 26
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_parse_language_cookie(self):
        """
        Now test that we parse language preferences stored in a cookie correctly.
        """
        g = get_language_from_request
        r = self.rf.get('/')
        r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'}
        r.META = {}
        self.assertEqual('pt-br', g(r))

        r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt'}
        r.META = {}
        self.assertEqual('pt', g(r))

        r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es'}
        r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'}
        self.assertEqual('es', g(r))

        # This test assumes there won't be a Django translation to a US
        # variation of the Spanish language, a safe assumption. When the
        # user sets it as the preferred language, the main 'es'
        # translation should be selected instead.
        r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es-us'}
        r.META = {}
        self.assertEqual(g(r), 'es')

        # This tests the following scenario: there isn't a main language (zh)
        # translation of Django but there is a translation to variation (zh-hans)
        # the user sets zh-hans as the preferred language, it should be selected
        # by Django without falling back nor ignoring it.
        r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'zh-hans'}
        r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'}
        self.assertEqual(g(r), 'zh-hans') 
Example 27
Project: avos   Author: CiscoSystems   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_initial(self):
        return {
            'language': self.request.session.get(
                settings.LANGUAGE_COOKIE_NAME,
                self.request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME,
                                         self.request.LANGUAGE_CODE)),
            'timezone': self.request.session.get(
                'django_timezone',
                self.request.COOKIES.get('django_timezone', 'UTC')),
            'pagesize': utils.get_page_size(self.request)} 
Example 28
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 4 votes vote down vote up
def get_language_from_request(request, check_path=False):
    """
    Analyzes the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language.

    If check_path is True, the URL path prefix will be checked for a language
    code, otherwise this is skipped for backwards compatibility.
    """
    if check_path:
        lang_code = get_language_from_path(request.path_info)
        if lang_code is not None:
            return lang_code

    supported_lang_codes = get_languages()

    if hasattr(request, 'session'):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)

    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass

    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    for accept_lang, unused in parse_accept_lang_header(accept):
        if accept_lang == '*':
            break

        if not language_code_re.search(accept_lang):
            continue

        try:
            return get_supported_language_variant(accept_lang)
        except LookupError:
            continue

    try:
        return get_supported_language_variant(settings.LANGUAGE_CODE)
    except LookupError:
        return settings.LANGUAGE_CODE 
Example 29
Project: bioforum   Author: reBiocoder   File: trans_real.py    License: MIT License 4 votes vote down vote up
def get_language_from_request(request, check_path=False):
    """
    Analyze the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language.

    If check_path is True, the URL path prefix will be checked for a language
    code, otherwise this is skipped for backwards compatibility.
    """
    if check_path:
        lang_code = get_language_from_path(request.path_info)
        if lang_code is not None:
            return lang_code

    supported_lang_codes = get_languages()

    if hasattr(request, 'session'):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)

    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass

    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    for accept_lang, unused in parse_accept_lang_header(accept):
        if accept_lang == '*':
            break

        if not language_code_re.search(accept_lang):
            continue

        try:
            return get_supported_language_variant(accept_lang)
        except LookupError:
            continue

    try:
        return get_supported_language_variant(settings.LANGUAGE_CODE)
    except LookupError:
        return settings.LANGUAGE_CODE 
Example 30
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: trans_real.py    License: MIT License 4 votes vote down vote up
def get_language_from_request(request, check_path=False):
    """
    Analyze the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language.

    If check_path is True, the URL path prefix will be checked for a language
    code, otherwise this is skipped for backwards compatibility.
    """
    if check_path:
        lang_code = get_language_from_path(request.path_info)
        if lang_code is not None:
            return lang_code

    supported_lang_codes = get_languages()

    if hasattr(request, 'session'):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)

    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass

    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    for accept_lang, unused in parse_accept_lang_header(accept):
        if accept_lang == '*':
            break

        if not language_code_re.search(accept_lang):
            continue

        try:
            return get_supported_language_variant(accept_lang)
        except LookupError:
            continue

    try:
        return get_supported_language_variant(settings.LANGUAGE_CODE)
    except LookupError:
        return settings.LANGUAGE_CODE