Python django.utils.translation.ngettext() Examples
The following are 23
code examples of django.utils.translation.ngettext().
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: __init__.py From astrobin with GNU Affero General Public License v3.0 | 6 votes |
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
Example #2
Source File: utils.py From bioforum with MIT License | 6 votes |
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)
Example #3
Source File: admin.py From django-x509 with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)), )
Example #4
Source File: utils.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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)
Example #5
Source File: formsets.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
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)
Example #6
Source File: wagtail_hooks.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
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, }
Example #7
Source File: wagtail_hooks.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
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, }
Example #8
Source File: password_validation.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
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}, )
Example #9
Source File: defaultfilters.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
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)
Example #10
Source File: formsets.py From bioforum with MIT License | 5 votes |
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)
Example #11
Source File: problem_manage.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
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]))
Example #12
Source File: problem_manage.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
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]))
Example #13
Source File: maximum_length_validator.py From substra-backend with Apache License 2.0 | 5 votes |
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}
Example #14
Source File: maximum_length_validator.py From substra-backend with Apache License 2.0 | 5 votes |
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}, )
Example #15
Source File: admin.py From django-x509 with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 ), )
Example #16
Source File: password_validation.py From bioforum with MIT License | 5 votes |
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}, )
Example #17
Source File: defaultfilters.py From bioforum with MIT License | 5 votes |
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)
Example #18
Source File: i18n.py From Hands-On-Application-Development-with-PyCharm with MIT License | 4 votes |
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 #19
Source File: pages.py From wagtail with BSD 3-Clause "New" or "Revised" License | 4 votes |
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 )
Example #20
Source File: snippets.py From wagtail with BSD 3-Clause "New" or "Revised" License | 4 votes |
def delete(request, app_label, model_name, pk=None): model = get_snippet_model_from_url_params(app_label, model_name) permission = get_permission_name('delete', model) if not request.user.has_perm(permission): return permission_denied(request) if pk: instances = [get_object_or_404(model, pk=unquote(pk))] else: ids = request.GET.getlist('id') instances = model.objects.filter(pk__in=ids) count = len(instances) if request.method == 'POST': for instance in instances: instance.delete() if count == 1: message_content = _("%(snippet_type)s '%(instance)s' deleted.") % { 'snippet_type': capfirst(model._meta.verbose_name), 'instance': instance } else: # This message is only used in plural form, but we'll define it with ngettext so that # languages with multiple plural forms can be handled correctly (or, at least, as # correctly as possible within the limitations of verbose_name_plural...) message_content = ngettext( "%(count)d %(snippet_type)s deleted.", "%(count)d %(snippet_type)s deleted.", count ) % { 'snippet_type': capfirst(model._meta.verbose_name_plural), 'count': count } messages.success(request, message_content) for fn in hooks.get_hooks('after_delete_snippet'): result = fn(request, instances) if hasattr(result, 'status_code'): return result return redirect('wagtailsnippets:list', app_label, model_name) return TemplateResponse(request, 'wagtailsnippets/snippets/confirm_delete.html', { 'model_opts': model._meta, 'count': count, 'instances': instances, 'submit_url': ( reverse('wagtailsnippets:delete-multiple', args=(app_label, model_name)) + '?' + urlencode([('id', instance.pk) for instance in instances]) ), })
Example #21
Source File: tasks.py From connect with MIT License | 4 votes |
def send_daily_digest_notification(user_id): """Send a daily digest notification for an individual user""" notifications = Notification.objects.filter( recipient_id=user_id, consumed=False, # Only send notifications for approved messages, otherwise leave the # messages pending message__status='approved', subscription__period='daily' ).select_related( 'recipient', 'message', 'message__thread', 'message__thread__group', 'message__thread__group__group' ).order_by('-message__thread', '-message__pk') # To reduce the number of `count` and `exists` queries, do the count once # and base as much logic around that count as possible. total_notifications = notifications.count() if not total_notifications: return recipient = notifications[0].recipient context = { 'notifications': notifications, 'recipient': recipient, 'email': recipient.email } text = render_to_string('notifications/email/email_digest.txt', context) html = render_to_string('notifications/email/email_digest.html', context) subject = u'Your {brand} {day} Digest - {num} New {word}'.format( brand=settings.BRAND_TITLE, day=now().strftime('%A'), num=total_notifications, word=ngettext('Message', 'Messages', total_notifications) ) send_email( email=recipient.email, from_email=settings.DEFAULT_FROM_EMAIL, subject=subject, text=text, html=html ) notifications.update(consumed=True)
Example #22
Source File: tasks.py From connect with MIT License | 4 votes |
def send_moderation_notification(group_owner_id, top_current_hour_iso): """Send an individual moderation notification""" from open_connect.accounts.models import User owner = User.objects.get(pk=group_owner_id) top_current_hour = parse_datetime(top_current_hour_iso) # Find the last time we would've used as a cut off as a message # moderation notification time notification_start = top_current_hour - timedelta( hours=owner.moderator_notification_period) # Grab all the messages that were modified before the current top hour and # after the last cut-off point for messages all_messages = owner.messages_to_moderate total_new_messages = all_messages.filter( modified_at__lt=top_current_hour, modified_at__gte=notification_start ).count() # We don't want to re-notify users of the same pending messages, so we need # to bail out here if there are no new pending messages if total_new_messages == 0: return # We'll include the total number of pending messages in the template total_messages = all_messages.count() context = { 'total_messages': total_messages, 'total_new_messages': total_new_messages, 'recipient': owner, 'email': owner.email } subject = u"You have {count} new {word} to moderate on Connect".format( count=total_new_messages, word=ngettext('message', 'messages', total_new_messages)) text = render_to_string( 'notifications/email/moderator_notification.txt', context) html = render_to_string( 'notifications/email/moderator_notification.html', context) send_email( email=owner.email, from_email=settings.DEFAULT_FROM_EMAIL, subject=subject, text=text, html=html )
Example #23
Source File: i18n.py From bioforum with MIT License | 4 votes |
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