Python django.utils.translation.get_language_from_request() Examples

The following are 25 code examples of django.utils.translation.get_language_from_request(). 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 also want to check out all available functions/classes of the module django.utils.translation , or try the search function .
Example #1
Source File: middleware.py    From arguman.org with GNU Affero General Public License v3.0 6 votes vote down vote up
def redirect_homepage(self, request):
        if request.path not in settings.REDIRECTED_PATHS:
            return

        language = get_language_from_request(request)

        if language not in self.LANGUAGES:
            language = settings.DEFAULT_LANGUAGE

        querystring = request.META.get('QUERY_STRING', '')
        if querystring:
            querystring = '?' + querystring

        return HttpResponseRedirect(
            ''.join([
                'http://', language, '.', settings.BASE_DOMAIN,
                request.path, querystring
            ])
        ) 
Example #2
Source File: override.py    From zing with GNU General Public License v3.0 6 votes vote down vote up
def get_language_from_request(request, check_path=False):
    """Try to get the user's preferred language by first checking the
    cookie and then by checking the HTTP language headers.

    If all fails, try fall back to default language.
    """
    supported = dict(supported_langs())
    for lang_getter in (
        get_lang_from_session,
        get_lang_from_cookie,
        get_lang_from_http_header,
    ):
        lang = lang_getter(request, supported)
        if lang is not None:
            return lang
    from django.conf import settings

    return settings.LANGUAGE_CODE 
Example #3
Source File: categories.py    From richie with MIT License 6 votes vote down vote up
def retrieve(self, request, pk, version, kind):
        """
        Return a single item by ID
        """
        # Wrap the ES get in a try/catch to we control the exception we emit — it would
        # raise and end up in a 500 error otherwise
        try:
            query_response = ES_CLIENT.get(
                index=self._meta.indexer.index_name,
                doc_type=self._meta.indexer.document_type,
                id=pk,
            )
        except NotFoundError:
            raise NotFound

        # Format a clean category object as a response
        return Response(
            self._meta.indexer.format_es_object_for_api(
                query_response,
                # Get the best language we can return multilingual fields in
                get_language_from_request(request),
            )
        ) 
Example #4
Source File: common.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def tracker_context(request, qdict=None):
    starttime = datetime.datetime.now()
    language = translation.get_language_from_request(request)
    translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()
    profile = None
    qdict = qdict or {}
    qdict.update(
        {
            'djangoversion': dv(),
            'pythonversion': pv(),
            'user': request.user,
            'profile': profile,
            'next': request.POST.get('next', request.GET.get('next', request.path)),
            'starttime': starttime,
            'events': tracker.models.Event.objects.all(),
            'settings': settings,
        }
    )
    qdict.setdefault('event', viewutil.get_event(None))
    qdict.setdefault('user', request.user)
    return qdict 
Example #5
Source File: categories.py    From richie with MIT License 5 votes vote down vote up
def autocomplete(self, request, version, kind):
        """
        Use the "completion" field on the categories mapping & objects to provide autocomplete
        functionality through an API endpoint.
        We cannot reuse the `AutocompleteMixin` as it does not handle "kinds" as categories need.
        """
        # Get a hold of the relevant indexer
        indexer = self._meta.indexer

        # Query our specific ES completion field
        autocomplete_query_response = ES_CLIENT.search(
            index=indexer.index_name,
            doc_type=indexer.document_type,
            body={
                "suggest": {
                    "categories": {
                        "prefix": request.query_params["query"],
                        "completion": {
                            "contexts": {"kind": [kind]},
                            "field": "complete.{:s}".format(
                                get_language_from_request(request)
                            ),
                        },
                    }
                }
            },
        )

        # Build a response array from the list of completion options
        return Response(
            [
                indexer.format_es_document_for_autocomplete(
                    option, get_language_from_request(request)
                )
                for option in autocomplete_query_response["suggest"]["categories"][0][
                    "options"
                ]
            ]
        ) 
Example #6
Source File: globals.py    From eoj3 with MIT License 5 votes vote down vote up
def get_current_language(context):
  return translation.get_language_from_request(context['request']) 
Example #7
Source File: functions.py    From avos with Apache License 2.0 5 votes vote down vote up
def add_logout_reason(request, response, reason):
    # Store the translated string in the cookie
    lang = translation.get_language_from_request(request)
    with translation.override(lang):
        reason = unicode(reason).encode('utf-8')
        response.set_cookie('logout_reason', reason, max_age=10) 
Example #8
Source File: locale_middleware.py    From speakerfight with MIT License 5 votes vote down vote up
def process_request(self, request):
        language = translation.get_language_from_request(request)

        if request.user.is_authenticated() and request.user.profile.language:
            language = request.user.profile.language

        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #9
Source File: utils.py    From djangocms-rest-api with MIT License 5 votes vote down vote up
def language(self):
        return get_language_from_request(self.request, check_path=True) 
Example #10
Source File: views.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_global_context(request, enterprise_customer=None):
    """
    Get the set of variables that are needed by default across views.
    """
    platform_name = get_configuration_value("PLATFORM_NAME", settings.PLATFORM_NAME)
    # pylint: disable=no-member
    context = {
        'enterprise_customer': enterprise_customer,
        'LMS_SEGMENT_KEY': settings.LMS_SEGMENT_KEY,
        'LANGUAGE_CODE': get_language_from_request(request),
        'tagline': get_configuration_value("ENTERPRISE_TAGLINE", settings.ENTERPRISE_TAGLINE),
        'platform_description': get_configuration_value(
            "PLATFORM_DESCRIPTION",
            settings.PLATFORM_DESCRIPTION,
        ),
        'LMS_ROOT_URL': settings.LMS_ROOT_URL,
        'platform_name': platform_name,
        'header_logo_alt_text': _('{platform_name} home page').format(platform_name=platform_name),
        'welcome_text': constants.WELCOME_TEXT.format(platform_name=platform_name),
    }

    if enterprise_customer is not None:
        context.update({
            'enterprise_welcome_text': constants.ENTERPRISE_WELCOME_TEXT.format(
                enterprise_customer_name=enterprise_customer.name,
                platform_name=platform_name,
                strong_start='<strong>',
                strong_end='</strong>',
                line_break='<br/>',
                privacy_policy_link_start="<a href='{pp_url}' target='_blank'>".format(
                    pp_url=get_configuration_value('PRIVACY', 'https://www.edx.org/edx-privacy-policy', type='url'),
                ),
                privacy_policy_link_end="</a>",
            ),
        })

    return context 
Example #11
Source File: models.py    From devops with MIT License 5 votes vote down vote up
def __init__(self, request=None):
        self.user = AnonymousUser()
        self.timezone = settings.TIME_ZONE
        if request is None:
            self.language = settings.LANGUAGE_CODE
        else:
            self.language = translation.get_language_from_request(request, check_path=True) 
Example #12
Source File: models.py    From devops with MIT License 5 votes vote down vote up
def create(cls, request=None, **kwargs):
        create_email = kwargs.pop("create_email", True)
        confirm_email = kwargs.pop("confirm_email", None)
        account = cls(**kwargs)
        if "language" not in kwargs:
            if request is None:
                account.language = settings.LANGUAGE_CODE
            else:
                account.language = translation.get_language_from_request(request, check_path=True)
        account.save()
        if create_email and account.user.email:
            kwargs = {"primary": True}
            if confirm_email is not None:
                kwargs["confirm"] = confirm_email
        return account 
Example #13
Source File: middleware.py    From devops with MIT License 5 votes vote down vote up
def get_language_for_user(self, request):
        if request.user.is_authenticated():
            try:
                account = Account.objects.get(user=request.user)
                return account.language
            except Account.DoesNotExist:
                pass
        return translation.get_language_from_request(request) 
Example #14
Source File: locale.py    From python2017 with MIT License 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #15
Source File: locale.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def process_request(self, request):
        language = translation.get_language_from_request(
            request, check_path=self.is_language_prefix_patterns_used)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #16
Source File: locale.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def process_request(self, request):
        check_path = self.is_language_prefix_patterns_used()
        language = translation.get_language_from_request(
            request, check_path=check_path)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #17
Source File: viewsets.py    From richie with MIT License 5 votes vote down vote up
def autocomplete(self, request, version):
        """
        Use the "completion" field on the organization mapping & objects to provide autocomplete
        functionality through an API endpoint.
        """
        # This mixin is intended to be used on ViewSets. It requires a _meta attribute holding
        # the relevant indexer
        indexer = self._meta.indexer

        # Query our specific ES completion field
        autocomplete_query_response = ES_CLIENT.search(
            index=indexer.index_name,
            doc_type=indexer.document_type,
            body={
                "suggest": {
                    "organizations": {
                        "prefix": request.query_params["query"],
                        "completion": {
                            "field": "complete.{:s}".format(
                                get_language_from_request(request)
                            )
                        },
                    }
                }
            },
        )

        # Build a response array from the list of completion options
        return Response(
            [
                indexer.format_es_document_for_autocomplete(
                    option, get_language_from_request(request)
                )
                for option in autocomplete_query_response["suggest"]["organizations"][
                    0
                ]["options"]
            ]
        ) 
Example #18
Source File: locale.py    From python with Apache License 2.0 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #19
Source File: locale.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #20
Source File: override.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def hijack_translation():
    """Sabotage Django's fascist linguistical regime."""
    # Override functions that check if language is known to Django
    translation.check_for_language = lambda lang_code: True
    trans_real.check_for_language = lambda lang_code: True
    translation.get_language_from_request = get_language_from_request

    # Override django's inadequate bidi detection
    translation.get_language_bidi = get_language_bidi 
Example #21
Source File: locale.py    From bioforum with MIT License 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #22
Source File: locale.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def process_request(self, request):
        check_path = self.is_language_prefix_patterns_used()
        language = translation.get_language_from_request(
            request, check_path=check_path)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #23
Source File: categories.py    From richie with MIT License 4 votes vote down vote up
def list(self, request, version, kind):
        """
        Category search endpoint: pass query params to ElasticSearch so it filters categories
        and returns a list of matching items
        """
        # Instantiate the form to allow validation/cleaning
        params_form = self._meta.indexer.form(data=request.query_params)

        # Return a 400 with error information if the query params are not valid
        if not params_form.is_valid():
            return Response(status=400, data={"errors": params_form.errors})

        limit, offset, query = params_form.build_es_query(kind=kind)

        try:
            # pylint: disable=unexpected-keyword-arg
            query_response = ES_CLIENT.search(
                _source=getattr(self._meta.indexer, "display_fields", "*"),
                index=self._meta.indexer.index_name,
                doc_type=self._meta.indexer.document_type,
                body=query,
                # Directly pass meta-params through as arguments to the ES client
                from_=offset,
                size=limit or getattr(settings, "RICHIE_ES_PAGE_SIZE", ES_PAGE_SIZE),
            )
        except NotFoundError:
            raise NotFound

        # Format the response in a consumer-friendly way
        # NB: if there are 0 hits the query_response is formatted the exact same way, only the
        # .hits.hits array is empty.
        response_object = {
            "meta": {
                "count": len(query_response["hits"]["hits"]),
                "offset": offset,
                "total_count": query_response["hits"]["total"],
            },
            "objects": [
                self._meta.indexer.format_es_object_for_api(
                    category,
                    # Get the best language we can return multilingual fields in
                    get_language_from_request(request),
                )
                for category in query_response["hits"]["hits"]
            ],
        }

        return Response(response_object)

    # pylint: disable=no-self-use,invalid-name,unused-argument 
Example #24
Source File: __init__.py    From anytask with MIT License 4 votes vote down vote up
def register(self, request, **kwargs):
        """
        Given a username, email address and password, register a new
        user account, which will initially be inactive.

        Along with the new ``User`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``User``, containing the activation key which
        will be used for this account.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """
        username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
        first_name, last_name, show_email = kwargs['first_name'], kwargs['last_name'], kwargs['show_email']
        #invite = get_object_or_404(Invite, key=invite_key)

        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                                    password, site)

        new_user.first_name = first_name
        new_user.last_name = last_name
        new_user.save()

        new_user_profile = UserProfile.objects.get(user=new_user)
        new_user_profile.show_email = show_email
        new_user_profile.language = get_language_from_request(request)
        new_user_profile.save()

        #if invite.group:
        #    invite.group.students.add(new_user)
        #invite.invited_user = new_user
        #invite.save()

        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user 
Example #25
Source File: __init__.py    From anytask with MIT License 4 votes vote down vote up
def register(self, request, **kwargs):
        """
        Given a username, email address and password, register a new
        user account, which will initially be inactive.

        Along with the new ``User`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``User``, containing the activation key which
        will be used for this account.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """
        username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
        first_name, last_name, show_email = kwargs['first_name'], kwargs['last_name'], kwargs['show_email']
        #invite = get_object_or_404(Invite, key=invite_key)

        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                                    password, site)

        new_user.first_name = first_name
        new_user.last_name = last_name
        new_user.save()

        new_user_profile = UserProfile.objects.get(user=new_user)
        new_user_profile.show_email = show_email
        new_user_profile.language = get_language_from_request(request)
        new_user_profile.save()

        #if invite.group:
        #    invite.group.students.add(new_user)
        #invite.invited_user = new_user
        #invite.save()

        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user