当前位置: 首页>>代码示例>>Python>>正文


Python translation.ngettext方法代码示例

本文整理汇总了Python中django.utils.translation.ngettext方法的典型用法代码示例。如果您正苦于以下问题:Python translation.ngettext方法的具体用法?Python translation.ngettext怎么用?Python translation.ngettext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.translation的用法示例。


在下文中一共展示了translation.ngettext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: model_ngettext

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.
    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ngettext(singular, plural, n or 0) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:18,代码来源:utils.py

示例2: renew_cert

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def renew_cert(self, request, queryset):
        if request.POST.get('post'):
            renewed_rows = 0
            for cert in queryset:
                cert.renew()
                renewed_rows += 1
            message = ngettext(
                '%(renewed_rows)d Certificate has been successfully renewed',
                '%(renewed_rows)d Certificates have been successfully renewed',
                renewed_rows,
            ) % {'renewed_rows': renewed_rows}
            self.message_user(request, message)
        else:
            return render(
                request,
                'admin/django_x509/renew_confirmation.html',
                context=self.get_context(queryset, cert_count=len(queryset)),
            ) 
开发者ID:openwisp,项目名称:django-x509,代码行数:20,代码来源:admin.py

示例3: upload_max_revisions_error

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def upload_max_revisions_error(request, max_revisions, image):
    subscriptions_url = reverse('subscription_list')
    open_link = "<a href=\"%s\">" % subscriptions_url
    close_link = "</a>"
    msg_singular = "Sorry, but you have reached the maximum amount of allowed image revisions. Under your current subscription, the limit is %(max_revisions)s revision per image. %(open_link)sWould you like to upgrade?%(close_link)s"
    msg_plural = "Sorry, but you have reached the maximum amount of allowed image revisions. Under your current subscription, the limit is %(max_revisions)s revisions per image. %(open_link)sWould you like to upgrade?%(close_link)s"

    messages.error(request, _n(msg_singular, msg_plural, max_revisions) % {
        "max_revisions": max_revisions,
        "open_link": open_link,
        "close_link": close_link
    })

    return HttpResponseRedirect(image.get_absolute_url())


# VIEWS 
开发者ID:astrobin,项目名称:astrobin,代码行数:19,代码来源:__init__.py

示例4: full_clean

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def full_clean(self):
        """
        Clean all of self.data and populate self._errors and
        self._non_form_errors.
        """
        self._errors = []
        self._non_form_errors = self.error_class()
        empty_forms_count = 0

        if not self.is_bound:  # Stop further processing.
            return
        for i in range(0, self.total_form_count()):
            form = self.forms[i]
            # Empty forms are unchanged forms beyond those with initial data.
            if not form.has_changed() and i >= self.initial_form_count():
                empty_forms_count += 1
            # Accessing errors calls full_clean() if necessary.
            # _should_delete_form() requires cleaned_data.
            form_errors = form.errors
            if self.can_delete and self._should_delete_form(form):
                continue
            self._errors.append(form_errors)
        try:
            if (self.validate_max and
                    self.total_form_count() - len(self.deleted_forms) > self.max_num) or \
                    self.management_form.cleaned_data[TOTAL_FORM_COUNT] > self.absolute_max:
                raise ValidationError(ngettext(
                    "Please submit %d or fewer forms.",
                    "Please submit %d or fewer forms.", self.max_num) % self.max_num,
                    code='too_many_forms',
                )
            if (self.validate_min and
                    self.total_form_count() - len(self.deleted_forms) - empty_forms_count < self.min_num):
                raise ValidationError(ngettext(
                    "Please submit %d or more forms.",
                    "Please submit %d or more forms.", self.min_num) % self.min_num,
                    code='too_few_forms')
            # Give self.clean() a chance to do cross-form validation.
            self.clean()
        except ValidationError as e:
            self._non_form_errors = self.error_class(e.error_list) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:43,代码来源:formsets.py

示例5: filesizeformat

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def filesizeformat(bytes_):
    """
    Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
    102 bytes, etc.).
    """
    try:
        bytes_ = float(bytes_)
    except (TypeError, ValueError, UnicodeDecodeError):
        value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
        return avoid_wrapping(value)

    def filesize_number_format(value):
        return formats.number_format(round(value, 1), 1)

    KB = 1 << 10
    MB = 1 << 20
    GB = 1 << 30
    TB = 1 << 40
    PB = 1 << 50

    negative = bytes_ < 0
    if negative:
        bytes_ = -bytes_  # Allow formatting of negative numbers.

    if bytes_ < KB:
        value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_}
    elif bytes_ < MB:
        value = gettext("%s KB") % filesize_number_format(bytes_ / KB)
    elif bytes_ < GB:
        value = gettext("%s MB") % filesize_number_format(bytes_ / MB)
    elif bytes_ < TB:
        value = gettext("%s GB") % filesize_number_format(bytes_ / GB)
    elif bytes_ < PB:
        value = gettext("%s TB") % filesize_number_format(bytes_ / TB)
    else:
        value = gettext("%s PB") % filesize_number_format(bytes_ / PB)

    if negative:
        value = "-%s" % value
    return avoid_wrapping(value) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:42,代码来源:defaultfilters.py

示例6: validate

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def validate(self, password, user=None):
        if len(password) < self.min_length:
            raise ValidationError(
                ngettext(
                    "This password is too short. It must contain at least %(min_length)d character.",
                    "This password is too short. It must contain at least %(min_length)d characters.",
                    self.min_length
                ),
                code='password_too_short',
                params={'min_length': self.min_length},
            ) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:13,代码来源:password_validation.py

示例7: renew_ca

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def renew_ca(self, request, queryset):
        if request.POST.get('post'):
            renewed_rows = 0
            for ca in queryset:
                ca.renew()
                renewed_rows += 1
            message = ngettext(
                (
                    '%(renewed_rows)d CA and its related certificates have '
                    'been successfully renewed'
                ),
                (
                    '%(renewed_rows)d CAs and their related '
                    'certificates have been successfully renewed'
                ),
                renewed_rows,
            ) % {'renewed_rows': renewed_rows}
            self.message_user(request, message)
        else:
            data = dict()
            ca_count = 0
            cert_count = 0
            for ca in queryset:
                ca_count += 1
                certs = ca.cert_set.all()
                cert_count += len(certs)
                data[ca] = certs
            return render(
                request,
                'admin/django_x509/renew_confirmation.html',
                context=self.get_context(
                    data, ca_count=ca_count, cert_count=cert_count
                ),
            ) 
开发者ID:openwisp,项目名称:django-x509,代码行数:36,代码来源:admin.py

示例8: validate

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def validate(self, password, user=None):
        if len(password) > self.max_length:
            raise ValidationError(
                ngettext(
                    "This password is too long. It must contain a maximum of %(max_length)d character.",
                    "This password is too long. It must contain a maximum of %(max_length)d characters.",
                    self.max_length
                ),
                code='password_too_long',
                params={'max_length': self.max_length},
            ) 
开发者ID:SubstraFoundation,项目名称:substra-backend,代码行数:13,代码来源:maximum_length_validator.py

示例9: get_help_text

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def get_help_text(self):
        return ngettext(
            "Your password must contain a maximum of %(max_length)d character.",
            "Your password must contain a maximum of %(max_length)d characters.",
            self.max_length
        ) % {'max_length': self.max_length} 
开发者ID:SubstraFoundation,项目名称:substra-backend,代码行数:8,代码来源:maximum_length_validator.py

示例10: rejudge_success

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def rejudge_success(request, problem, task_id):
    count = AsyncResult(task_id).result
    if not isinstance(count, int):
        raise Http404()
    messages.success(request, ngettext('Successfully scheduled %d submission for rejudging.',
                                       'Successfully scheduled %d submissions for rejudging.', count) % (count,))
    return HttpResponseRedirect(reverse('problem_manage_submissions', args=[problem])) 
开发者ID:DMOJ,项目名称:online-judge,代码行数:9,代码来源:problem_manage.py

示例11: rescore_success

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def rescore_success(request, problem, task_id):
    count = AsyncResult(task_id).result
    if not isinstance(count, int):
        raise Http404()
    messages.success(request, ngettext('%d submission were successfully rescored.',
                                       '%d submissions were successfully rescored.', count) % (count,))
    return HttpResponseRedirect(reverse('problem_manage_submissions', args=[problem])) 
开发者ID:DMOJ,项目名称:online-judge,代码行数:9,代码来源:problem_manage.py

示例12: describe_collection_docs

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def describe_collection_docs(collection):
    images_count = get_image_model().objects.filter(collection=collection).count()
    if images_count:
        url = reverse('wagtailimages:index') + ('?collection_id=%d' % collection.id)
        return {
            'count': images_count,
            'count_text': ngettext(
                "%(count)s image",
                "%(count)s images",
                images_count
            ) % {'count': images_count},
            'url': url,
        } 
开发者ID:wagtail,项目名称:wagtail,代码行数:15,代码来源:wagtail_hooks.py

示例13: describe_collection_docs

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def describe_collection_docs(collection):
    docs_count = get_document_model().objects.filter(collection=collection).count()
    if docs_count:
        url = reverse('wagtaildocs:index') + ('?collection_id=%d' % collection.id)
        return {
            'count': docs_count,
            'count_text': ngettext(
                "%(count)s document",
                "%(count)s documents",
                docs_count
            ) % {'count': docs_count},
            'url': url,
        } 
开发者ID:wagtail,项目名称:wagtail,代码行数:15,代码来源:wagtail_hooks.py

示例14: render

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
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 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:56,代码来源:i18n.py

示例15: __init__

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import ngettext [as 别名]
def __init__(self, *args, **kwargs):
        # CopyPage must be passed a 'page' kwarg indicating the page to be copied
        self.page = kwargs.pop('page')
        self.user = kwargs.pop('user', None)
        can_publish = kwargs.pop('can_publish')
        super().__init__(*args, **kwargs)
        self.fields['new_title'] = forms.CharField(initial=self.page.title, label=_("New title"))
        allow_unicode = getattr(settings, 'WAGTAIL_ALLOW_UNICODE_SLUGS', True)
        self.fields['new_slug'] = forms.SlugField(initial=self.page.slug, label=_("New slug"), allow_unicode=allow_unicode)
        self.fields['new_parent_page'] = forms.ModelChoiceField(
            initial=self.page.get_parent(),
            queryset=Page.objects.all(),
            widget=widgets.AdminPageChooser(can_choose_root=True, user_perms='copy_to'),
            label=_("New parent page"),
            help_text=_("This copy will be a child of this given parent page.")
        )
        pages_to_copy = self.page.get_descendants(inclusive=True)
        subpage_count = pages_to_copy.count() - 1
        if subpage_count > 0:
            self.fields['copy_subpages'] = forms.BooleanField(
                required=False, initial=True, label=_("Copy subpages"),
                help_text=ngettext(
                    "This will copy %(count)s subpage.",
                    "This will copy %(count)s subpages.",
                    subpage_count) % {'count': subpage_count})

        if can_publish:
            pages_to_publish_count = pages_to_copy.live().count()
            if pages_to_publish_count > 0:
                # In the specific case that there are no subpages, customise the field label and help text
                if subpage_count == 0:
                    label = _("Publish copied page")
                    help_text = _("This page is live. Would you like to publish its copy as well?")
                else:
                    label = _("Publish copies")
                    help_text = ngettext(
                        "%(count)s of the pages being copied is live. Would you like to publish its copy?",
                        "%(count)s of the pages being copied are live. Would you like to publish their copies?",
                        pages_to_publish_count) % {'count': pages_to_publish_count}

                self.fields['publish_copies'] = forms.BooleanField(
                    required=False, initial=True, label=label, help_text=help_text
                ) 
开发者ID:wagtail,项目名称:wagtail,代码行数:45,代码来源:pages.py


注:本文中的django.utils.translation.ngettext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。