Python django.utils.translation.pgettext() Examples

The following are 20 code examples of django.utils.translation.pgettext(). 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: extensions.py    From jinja2-django-tags with MIT License 6 votes vote down vote up
def _make_blocktrans(self, singular, plural=None, context=None, trans_vars=None,
                         count_var=None):
        if trans_vars is None:
            trans_vars = {}  # pragma: no cover
        if self.environment.finalize:
            finalized_trans_vars = {
                key: self.environment.finalize(val) for key, val in trans_vars.items()
            }
        else:
            finalized_trans_vars = trans_vars
        if plural is None:
            if context is None:
                return ugettext(force_text(singular)) % finalized_trans_vars
            else:
                return pgettext(force_text(context), force_text(singular)) % finalized_trans_vars
        else:
            if context is None:
                return ungettext(
                    force_text(singular), force_text(plural), trans_vars[count_var]
                ) % finalized_trans_vars
            else:
                return npgettext(
                    force_text(context), force_text(singular), force_text(plural),
                    trans_vars[count_var]
                ) % finalized_trans_vars 
Example #2
Source File: submission.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        submission = kwargs.pop('obj', None)
        label = None
        if submission:
            if db_field.name == 'participation':
                kwargs['queryset'] = ContestParticipation.objects.filter(user=submission.user,
                                                                         contest__problems=submission.problem) \
                    .only('id', 'contest__name')

                def label(obj):
                    return obj.contest.name
            elif db_field.name == 'problem':
                kwargs['queryset'] = ContestProblem.objects.filter(problem=submission.problem) \
                    .only('id', 'problem__name', 'contest__name')

                def label(obj):
                    return pgettext('contest problem', '%(problem)s in %(contest)s') % {
                        'problem': obj.problem.name, 'contest': obj.contest.name,
                    }
        field = super(ContestSubmissionInline, self).formfield_for_dbfield(db_field, **kwargs)
        if label is not None:
            field.label_from_instance = label
        return field 
Example #3
Source File: text.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate) 
Example #4
Source File: text.py    From python2017 with MIT License 5 votes vote down vote up
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate) 
Example #5
Source File: text.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate) 
Example #6
Source File: text.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate) 
Example #7
Source File: i18n.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        data = dict([(v, _render_value_in_context(context.get(v, ''), context)) for v in vars])
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError("'blocktrans' is unable to format "
                    "string returned by gettext: %r using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        return result 
Example #8
Source File: text.py    From python with Apache License 2.0 5 votes vote down vote up
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate) 
Example #9
Source File: text.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate) 
Example #10
Source File: text.py    From bioforum with MIT License 5 votes vote down vote up
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate) 
Example #11
Source File: extensions.py    From jinja2-django-tags with MIT License 5 votes vote down vote up
def _parse_trans(self, parser, lineno):
        string = parser.stream.expect(lexer.TOKEN_STRING)
        string = nodes.Const(string.value, lineno=string.lineno)
        is_noop = False
        context = None
        as_var = None
        for token in iter(lambda: parser.stream.next_if(lexer.TOKEN_NAME), None):
            if token.value == 'noop' and not is_noop:
                if context is not None:
                    parser.fail("noop translation can't have context", lineno=token.lineno)
                is_noop = True
            elif token.value == 'context' and context is None:
                if is_noop:
                    parser.fail("noop translation can't have context", lineno=token.lineno)
                context = parser.stream.expect(lexer.TOKEN_STRING)
                context = nodes.Const(context.value, lineno=context.lineno)
            elif token.value == 'as' and as_var is None:
                as_var = parser.stream.expect(lexer.TOKEN_NAME)
                as_var = nodes.Name(as_var.value, 'store', lineno=as_var.lineno)
            else:
                parser.fail("expected 'noop', 'context' or 'as'", lineno=token.lineno)
        if is_noop:
            output = string
        elif context is not None:
            func = nodes.Name('pgettext', 'load', lineno=lineno)
            output = nodes.Call(func, [context, string], [], None, None, lineno=lineno)
        else:
            func = nodes.Name('gettext', 'load')
            output = nodes.Call(func, [string], [], None, None, lineno=lineno)

        if as_var is None:
            return nodes.Output([output], lineno=lineno)
        else:
            return nodes.Assign(as_var, output, lineno=lineno) 
Example #12
Source File: extensions.py    From jinja2-django-tags with MIT License 5 votes vote down vote up
def __init__(self, environment):
        super(DjangoI18n, self).__init__(environment)
        environment.globals['_'] = ugettext
        environment.globals['gettext'] = ugettext
        environment.globals['pgettext'] = pgettext 
Example #13
Source File: i18n.py    From Hands-On-Application-Development-with-PyCharm with MIT License 4 votes vote down vote up
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ngettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.gettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    "'blocktrans' is unable to format string returned by gettext: %r using %r"
                    % (result, data)
                )
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result 
Example #14
Source File: listing.py    From pasportaservo with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_queryset(self):
        most_recent_moniker, most_recent = pgettext("value::plural", "MOST RECENT"), False
        if self.query in (most_recent_moniker, most_recent_moniker.replace(" ", "_")):
            most_recent = True
            self.query = ''

        qs = (
            self.queryset
            .select_related(None)
            .defer('description', 'family_members_visibility')
            .select_related('owner', 'owner__user')
            .defer('owner__description', 'owner__email_visibility')
        )

        self.result = geocode(self.query)
        if self.query and self.result.point:
            if any([self.result.country and not self.result.country_code, self.result.state, self.result.city]):
                return (qs
                        .annotate(distance=Distance('location', self.result.point))
                        .order_by('distance'))
            elif self.result.country:  # We assume it's a country
                self.paginate_first_by = 50
                self.paginate_orphans = 5
                self.country_search = True
                return (qs
                        .filter(country=self.result.country_code.upper())
                        .order_by('-owner__user__last_login', '-id'))
        position = geocoder.ip(self.request.META['HTTP_X_REAL_IP']
                               if settings.ENVIRONMENT != 'DEV'
                               else "188.166.58.162")
        position.point = Point(position.xy, srid=SRID) if position.xy else None
        logging.getLogger('PasportaServo.geo').debug(
            "User's position: %s, %s",
            position.address if position.ok and position.address else "UNKNOWN",
            position.xy if position.ok else position.error
        )
        if position.point and not most_recent:
            # Results are sorted by distance from user's current location, but probably
            # it is better not to creep users out by unexpectedly using their location.
            qs = qs.annotate(internal_distance=Distance('location', position.point)).order_by('internal_distance')
        else:
            qs = qs.order_by('-owner__user__last_login', '-id')
        return qs 
Example #15
Source File: i18n.py    From python with Apache License 2.0 4 votes vote down vote up
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    "'blocktrans' is unable to format string returned by gettext: %r using %r"
                    % (result, data)
                )
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result 
Example #16
Source File: i18n.py    From bioforum with MIT License 4 votes vote down vote up
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ngettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.gettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    "'blocktrans' is unable to format string returned by gettext: %r using %r"
                    % (result, data)
                )
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result 
Example #17
Source File: i18n.py    From openhgsenti with Apache License 2.0 4 votes vote down vote up
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError("'blocktrans' is unable to format "
                    "string returned by gettext: %r using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result 
Example #18
Source File: i18n.py    From python2017 with MIT License 4 votes vote down vote up
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    "'blocktrans' is unable to format string returned by gettext: %r using %r"
                    % (result, data)
                )
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result 
Example #19
Source File: i18n.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError("'blocktrans' is unable to format "
                    "string returned by gettext: %r using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        return result 
Example #20
Source File: views.py    From foundation.mozilla.org with Mozilla Public License 2.0 4 votes vote down vote up
def product_view(request, slug):
    product = get_object_or_404(Product, slug=slug).specific

    if product.draft and not request.user.is_authenticated:
        raise Http404("Product does not exist")

    product_dict = product.to_dict()
    criteria = [
        'uses_encryption',
        'security_updates',
        'strong_password',
        'manage_vulnerabilities',
        'privacy_policy',
    ]
    total_score = 0
    num_criteria = len(criteria)

    # Calculate the minimum security score
    for i in range(num_criteria):
        value = product_dict[criteria[i]]
        if value == 'Yes':
            total_score += 1
        if value == 'NA':
            total_score += 0.5

    # make sure featured updates come first
    product_dict['updates'] = list(
        product.updates.all().order_by(
            '-featured',
            'pk'
        )
    )

    return render(request, 'product_page.html', {
        'categories': BuyersGuideProductCategory.objects.all(),
        'product': product_dict,
        'mediaUrl': MEDIA_URL,
        'coralTalkServerUrl': settings.CORAL_TALK_SERVER_URL,
        'pageTitle': pgettext(
            'This can be localized. This is a reference to the “*batteries not included” mention on toys.',
            '*privacy not included') + f' - {product.name}',
        'security_score': total_score,
        'full_security_score': num_criteria
    })