Python django.utils.translation.get_language() Examples

The following are 30 code examples of django.utils.translation.get_language(). 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: forms.py    From arguman.org with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_target(self):
        target_noun = self.cleaned_data['target_noun']

        try:
            noun = Noun.objects.get(
                text=target_noun,
                language=normalize_language_code(get_language())
            )
        except Noun.DoesNotExist:
            noun = Noun.objects.create(
                text=target_noun,
                is_active=False,
                language=normalize_language_code(get_language())
            )

        return noun 
Example #2
Source File: models.py    From arguman.org with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_public_newsfeed(self, offset, limit):
        """
        Fetches news items from the newsfeed database
        """
        language = self.get_language()

        parameters = {
            "news_type": {
                "$in": [NEWS_TYPE_CONTENTION,
                        NEWS_TYPE_PREMISE,
                        NEWS_TYPE_FALLACY]
            },
            "related_object.language": language
        }

        newsfeed = (Entry
                    .objects
                    .collection
                    .find(parameters)
                    .sort([("date_created", -1)])
                    .skip(offset)
                    .limit(limit))
        return map(Entry, newsfeed) 
Example #3
Source File: widgets.py    From bioforum with MIT License 6 votes vote down vote up
def media(self):
        extra = '' if settings.DEBUG else '.min'
        i18n_name = SELECT2_TRANSLATIONS.get(get_language())
        i18n_file = ('admin/js/vendor/select2/i18n/%s.js' % i18n_name,) if i18n_name else ()
        return forms.Media(
            js=(
                'admin/js/vendor/jquery/jquery%s.js' % extra,
                'admin/js/vendor/select2/select2.full%s.js' % extra,
            ) + i18n_file + (
                'admin/js/jquery.init.js',
                'admin/js/autocomplete.js',
            ),
            css={
                'screen': (
                    'admin/css/vendor/select2/select2%s.css' % extra,
                    'admin/css/autocomplete.css',
                ),
            },
        ) 
Example #4
Source File: models.py    From arguman.org with GNU Affero General Public License v3.0 6 votes vote down vote up
def channel(self):
        from nouns.models import Channel

        if self.related_nouns.exists():
            nouns = self.related_nouns.all()
        else:
            nouns = self.nouns.all()

        if not nouns:
            return

        channel = Channel.objects.filter(
            nouns__in=nouns,
            language=normalize_language_code(get_language())
        ).first()

        return channel 
Example #5
Source File: backends.py    From linkedevents with MIT License 6 votes vote down vote up
def forward_to_backends(self, method, *args, **kwargs):
        # forwards the desired backend method to all the language backends
        initial_language = translation.get_language()
        # retrieve unique backend name
        backends = []
        for language, _ in settings.LANGUAGES:
            using = '%s-%s' % (self.connection_alias, language)
            # Ensure each backend is called only once
            if using in backends:
                continue
            else:
                backends.append(using)
            translation.activate(language)
            backend = connections[using].get_backend()
            getattr(backend.parent_class, method)(backend, *args, **kwargs)

        if initial_language is not None:
            translation.activate(initial_language)
        else:
            translation.deactivate() 
Example #6
Source File: widgets.py    From dissemin with GNU Affero General Public License v3.0 6 votes vote down vote up
def media(self):
        """
        Construct Media as a dynamic property.
        .. Note:: For more information visit
            https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
        """
        lang = get_language()
        select2_js = (settings.SELECT2_JS,) if settings.SELECT2_JS else ()
        select2_css = (settings.SELECT2_CSS,) if settings.SELECT2_CSS else ()

        i18n_name = SELECT2_TRANSLATIONS.get(lang)
        if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
            i18n_name = None

        i18n_file = (
            ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),)
            if i18n_name
            else ()
        )

        return forms.Media(
            js=select2_js + i18n_file + (static("js/django_select2.js"), ),
            css={'screen': select2_css}
        ) 
Example #7
Source File: i18n.py    From xblock-utils with GNU Affero General Public License v3.0 6 votes vote down vote up
def merge_translation(self, context):
        """
        Context wrapper which modifies the given language's translation catalog using the i18n service, if found.
        """
        language = get_language()
        i18n_service = context.get('_i18n_service', None)
        if i18n_service:
            # Cache the original translation object to reduce overhead
            if language not in self._translations:
                self._translations[language] = trans_real.DjangoTranslation(language)

            translation = trans_real.translation(language)
            translation.merge(i18n_service)

        yield

        # Revert to original translation object
        if language in self._translations:
            trans_real._translations[language] = self._translations[language]  # pylint: disable=protected-access
            # Re-activate the current language to reset translation caches
            trans_real.activate(language) 
Example #8
Source File: urlresolvers.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def regex(self):
        """
        Returns a compiled regular expression, depending upon the activated
        language-code.
        """
        language_code = get_language()
        if language_code not in self._regex_dict:
            if isinstance(self._regex, six.string_types):
                regex = self._regex
            else:
                regex = force_text(self._regex)
            try:
                compiled_regex = re.compile(regex, re.UNICODE)
            except re.error as e:
                raise ImproperlyConfigured(
                    '"%s" is not a valid regular expression: %s' %
                    (regex, six.text_type(e)))

            self._regex_dict[language_code] = compiled_regex
        return self._regex_dict[language_code] 
Example #9
Source File: classified.py    From django-classified with MIT License 6 votes vote down vote up
def currency(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return ""

    # Using Babel's currency formatting
    # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency

    kwargs = {
        'currency': currency or CURRENCY,
        'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
    }

    return format_currency(value, **kwargs) 
Example #10
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 #11
Source File: currency_filters.py    From django-accounting with MIT License 6 votes vote down vote up
def currency_formatter(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return ""
    # Using Babel's currency formatting
    # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency
    currency = currency or settings.ACCOUNTING_DEFAULT_CURRENCY
    kwargs = {
        'currency': currency,
        'format': getattr(settings, 'CURRENCY_FORMAT', None),
        'locale': to_locale(get_language()),
    }
    return format_currency(value, **kwargs) 
Example #12
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_crowded_contentions(self):
        return Contention.objects.annotate(
            premise_count=Sum("premises"),
        ).filter(
            language=normalize_language_code(get_language()),
            premise_count__gt=0,
            **self.build_time_filters(date_field="date_creation")
        ).order_by("-premise_count")[:10] 
Example #13
Source File: i18n.py    From pycon with MIT License 5 votes vote down vote up
def make_localized_resolver(field_name: str):
    def resolver(root, info, language: Optional[str] = None) -> str:
        language = language or translation.get_language() or settings.LANGUAGE_CODE

        return getattr(root, field_name).localize(language)

    return resolver 
Example #14
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_text_file(self):
        language = get_language()
        return render_to_string("about-%s.md" % language) 
Example #15
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.ip_address = get_ip_address(self.request)
        form.instance.language = normalize_language_code(get_language())
        form.instance.is_published = True
        response = super(ArgumentCreationView, self).form_valid(form)
        form.instance.update_sibling_counts()
        form.instance.save_nouns()
        form.instance.save()
        return response 
Example #16
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_redirect_url(self, *args, **kwargs):
        argument = Contention.objects.annotate(
            premise_count=Count('premises')
        ).filter(
            premise_count__gt=2,
            language=normalize_language_code(get_language())
        ).order_by(
            '?'
        )[0]
        return argument.get_absolute_url() 
Example #17
Source File: models.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def related_contentions(self):
        if self.related_nouns.exists():
            source = self.related_nouns
        else:
            source = self.nouns

        nouns = source.prefetch_related('out_relations')
        noun_ids = set(nouns.values_list('pk', flat=True))

        for noun in nouns.all():
            relations = set(noun.out_relations.values_list('target', flat=True))
            noun_ids = noun_ids.union(relations)

        available_nouns = (
            Noun.objects.filter(
                language=normalize_language_code(get_language()),
                id__in=noun_ids
            ).annotate(
                contention_count=Count('contentions'),
            ).filter(
                contentions__is_published=True
            ).prefetch_related(
                'contentions'
            )
        )

        serialized = [{
            'noun': noun,
            'contentions': (
                noun
                .contentions
                .exclude(pk=self.pk)
                .values('title', 'slug')
                .order_by('?')  # find a proper way to randomize
                                # suggestions
                [:7]
            )
        } for noun in available_nouns]

        return filter(itemgetter('contentions'), serialized) 
Example #18
Source File: core_tags.py    From rdmo with Apache License 2.0 5 votes vote down vote up
def render_lang_template(template_name):
    loc = to_locale(get_language())
    lst = [
        template_name + '_' + loc + '.html',
        template_name + '_' + settings.LANGUAGES[0][0] + '.html',
        template_name + '_en.html',
        template_name + '.html'
    ]
    for el in lst:
        try:
            t = get_template(el)
            return t.render()
        except TemplateDoesNotExist:
            pass
    return '' 
Example #19
Source File: context_processors.py    From django-starter-project with MIT License 5 votes vote down vote up
def django_settings(request):

    return {
        "LANGUAGE": get_language(),
    } 
Example #20
Source File: core_tags.py    From rdmo with Apache License 2.0 5 votes vote down vote up
def i18n_switcher():
    string = ''
    for language, language_string in settings.LANGUAGES:
        url = reverse('i18n_switcher', args=[language])
        if language == translation.get_language():
            string += "<li><a href=\"%s\"><u>%s</u></a></li>" % (url, language_string)
        else:
            string += "<li><a href=\"%s\">%s</a></li>" % (url, language_string)
    return mark_safe(string) 
Example #21
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_supported_premises(self):
        return Premise.objects.annotate(
            supporter_count=Sum("supporters")
        ).filter(
            argument__language=get_language(),
            supporter_count__gt=0,
            **self.build_time_filters(date_field="date_creation")
        ).order_by("-supporter_count")[:50] 
Example #22
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_premises(self, paginate=True):
        keywords = self.request.GET.get('keywords')
        if not keywords or len(keywords) < 3:
            result = Premise.objects.none()
        else:
            result = (Premise.objects.filter(
                argument__language=normalize_language_code(get_language()),
                text__contains=keywords))
            if paginate:
                result = result[self.get_offset():self.get_limit()]
        return result 
Example #23
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        language = normalize_language_code(get_language())
        fallacies = (Report
                     .objects
                     .filter(reason__isnull=False,
                             contention__language=language)
                     .order_by('-id')
                     [self.get_offset():self.get_limit()])
        return super(FallaciesView, self).get_context_data(
            fallacies=fallacies,
            **kwargs) 
Example #24
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_channels(self):
        return Channel.objects.filter(
            language=normalize_language_code(get_language())
        ).order_by('order') 
Example #25
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        host = request.META['HTTP_HOST']

        if not host.startswith(settings.AVAILABLE_LANGUAGES):
            return redirect(self.object.get_full_url(), permanent=True)

        if not normalize_language_code(get_language()) == self.object.language:
            return redirect(self.object.get_full_url(), permanent=True)

        partial = request.GET.get('partial')
        level = request.GET.get('level')

        if partial:
            contention = self.object

            try:
                serialized = contention.partial_serialize(int(partial), self.request.user)
            except (StopIteration, ValueError):
                raise Http404

            return render(request, 'premises/tree.html', {
                'premises': serialized['premises'],
                'serialized': serialized,
                'level': int(level)
            })

        return super(ContentionDetailView, self).get(request, *args, **kwargs) 
Example #26
Source File: managers.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def language(self, language_code=None):
        if language_code is None:
            language_code = get_language()
        language_code = normalize_language_code(language_code)
        return self.filter(language=language_code) 
Example #27
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_supported_premises(self, user):
        return Premise.objects.filter(
            is_approved=True,
            user=user,
            argument__language=normalize_language_code(get_language())
        ).annotate(
            supporter_count=Count('supporters', distinct=True)
        ).filter(
            supporter_count__gt=0
        ).order_by(
            '-supporter_count'
        )[:10] 
Example #28
Source File: admin.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_form(self, request, obj=None, **kwargs):
        form = super(NounAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['language'].initial = normalize_language_code(get_language())
        return form 
Example #29
Source File: format_filters.py    From django-accounting with MIT License 5 votes vote down vote up
def percentage_formatter(value):
    if value or value == 0:
        kwargs = {
            'locale': to_locale(get_language()),
            'format': "#,##0.00 %",
        }
        return format_percent(value, **kwargs) 
Example #30
Source File: context_processors.py    From byro with Apache License 2.0 5 votes vote down vote up
def byro_information(request):
    ctx = {
        "config": Configuration.get_solo(),
        "pending_mails": EMail.objects.filter(sent__isnull=True).count(),
        "pending_transactions": Transaction.objects.unbalanced_transactions().count(),
        "log_end": LogEntry.objects.get_chain_end(),
        "effective_date_format": formats.get_format(
            "SHORT_DATE_FORMAT", lang=translation.get_language()
        ),
    }

    ctx["effective_date_format_js"] = (
        ctx["effective_date_format"]
        .replace("d", "dd")
        .replace("m", "mm")
        .replace("Y", "yyyy")
    )

    try:
        ctx["url_name"] = resolve(request.path_info).url_name
    except Http404:
        ctx["url_name"] = ""

    if settings.DEBUG:
        ctx["development_warning"] = True

    ctx["byro_version"] = get_version()

    return ctx