Here are the examples of the python api django.utils.translation.ungettext taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
134 Examples
3
Example 1
Project: site Source File: admin.py
def recalculate_cuemtime(self, request, queryset):
count = 0
for participation in queryset:
participation.update_cuemtime()
count += 1
self.message_user(request, ungettext('%d participation have times recalculated.',
'%d participations have times recalculated.',
count) % count)
3
Example 2
def filesizeformat(bytes):
"""
Formats 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):
return u"0 bytes"
if bytes < 1024:
return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
if bytes < 1024 * 1024:
return ugettext("%.1f KB") % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return ugettext("%.1f MB") % (bytes / (1024 * 1024))
return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
3
Example 3
Project: veyepar Source File: admin.py
def clear_locked(self, request, queryset):
rows_updated = queryset.update(locked=None)
msg = ungettext(
'Cleared locked timestamp in %(count)d %(name)s successfully.',
'Cleared locked timestamp in %(count)d %(name_plural)s successfully.',
rows_updated
) % {
'count': rows_updated,
'name': self.model._meta.verbose_name.title(),
'name_plural': self.model._meta.verbose_name_plural.title()
}
messages.success(request, msg)
3
Example 4
Project: django-oscar Source File: views.py
def remove_selected_products(self, request, products):
range = self.get_range()
for product in products:
range.remove_product(product)
num_products = len(products)
messages.success(request, ungettext("Removed %d product from range",
"Removed %d products from range",
num_products) % num_products)
return HttpResponseRedirect(self.get_success_url(request))
3
Example 5
def get_help_text(self):
return ungettext(
"Your password must contain at least %(min_length)d character.",
"Your password must contain at least %(min_length)d characters.",
self.min_length
) % {'min_length': self.min_length}
3
Example 6
@hooks.register('describe_collection_contents')
def describe_collection_docs(collection):
docs_count = get_docuement_model().objects.filter(collection=collection).count()
if docs_count:
url = urlresolvers.reverse('wagtaildocs:index') + ('?collection_id=%d' % collection.id)
return {
'count': docs_count,
'count_text': ungettext(
"%(count)s docuement",
"%(count)s docuements",
docs_count
) % {'count': docs_count},
'url': url,
}
3
Example 7
def get_short_description(self):
instance = self.get_plugin_instance()[0]
if not instance:
return ugettext("<Empty>")
column_count = len(self.child_plugin_instances or [])
column_count_str = ungettext(
"1 column",
"%(count)i columns",
column_count
) % {'count': column_count}
if self.classes:
return "{} ({})".format(
self.classes,
column_count_str
)
return column_count_str
3
Example 8
def _bulk_flag(self, queryset, action, done_message):
"""
Flag, approve, or remove some comments from an admin action. Actually
calls the `action` argument to perform the heavy lifting.
"""
n_comments = 0
for comment in queryset:
action(self.request, comment)
n_comments += 1
msg = ungettext('1 comment was successfully %(action)s.',
'%(count)s comments were successfully %(action)s.',
n_comments)
self.message_user(msg % {'count': n_comments, 'action': done_message(n_comments)}, 'success')
3
Example 9
@property
def nav_subtitle(self):
records = self._records[threading.currentThread()]
record_count = len(records)
return ungettext("%(count)s message", "%(count)s messages",
record_count) % {'count': record_count}
3
Example 10
def get_error_message(self):
"""
Returns this validator's error message.
"""
msg = ungettext("The new password must contain %d or more letter.",
"The new password must contain %d or more letters.",
self.get_min_count()) % self.get_min_count()
return msg
3
Example 11
Project: django-contrib-comments Source File: forms.py
def clean_comment(self):
"""
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
contain anything in PROFANITIES_LIST.
"""
comment = self.cleaned_data["comment"]
if (not getattr(settings, 'COMMENTS_ALLOW_PROFANITIES', False) and
getattr(settings, 'PROFANITIES_LIST', False)):
bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
if bad_words:
raise forms.ValidationError(ungettext(
"Watch your mouth! The word %s is not allowed here.",
"Watch your mouth! The words %s are not allowed here.",
len(bad_words)) % get_text_list(
['"%s%s%s"' % (i[0], '-' * (len(i) - 2), i[-1])
for i in bad_words], ugettext('and')))
return comment
3
Example 12
Project: django-nonrel Source File: forms.py
def clean_comment(self):
"""
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
contain anything in PROFANITIES_LIST.
"""
comment = self.cleaned_data["comment"]
if settings.COMMENTS_ALLOW_PROFANITIES == False:
bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
if bad_words:
plural = len(bad_words) > 1
raise forms.ValidationError(ungettext(
"Watch your mouth! The word %s is not allowed here.",
"Watch your mouth! The words %s are not allowed here.", plural) % \
get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and'))
return comment
3
Example 13
Project: modoboa Source File: domain.py
@login_required
@permission_required("admin.delete_domain")
def deldomain(request, dom_id):
keepdir = True if request.POST.get("keepdir", "false") == "true" else False
try:
mb = Mailbox.objects.get(user__id=request.user.id)
except Mailbox.DoesNotExist:
mb = None
dom = Domain.objects.get(pk=dom_id)
if not request.user.can_access(dom):
raise PermDeniedException
if mb and mb.domain == dom:
raise PermDeniedException(_("You can't delete your own domain"))
dom.delete(request.user, keepdir)
msg = ungettext("Domain deleted", "Domains deleted", 1)
return render_to_json_response(msg)
3
Example 14
Project: djangogirls Source File: admin.py
def payments_link(self, patron):
link = (
reverse('admin:patreonmanager_payment_changelist') +
'?patron_id__exact=%s' % patron.pk)
count = patron.payments.count()
return format_html(
'<a href="{}">{}</a>', link,
ungettext("%d payment", "%d payments", count) % count)
3
Example 15
Project: oioioi Source File: models.py
def _round_end_date_name_generator(obj):
max_round_extension = RoundTimeExtension.objects.filter(round=obj). \
aggregate(Max('extra_time'))['extra_time__max']
if max_round_extension is not None:
return ungettext("End of %(name)s (+ %(ext)d min)",
"End of %(name)s (+ %(ext)d mins)",
max_round_extension) % \
{'name': obj.name, 'ext': max_round_extension}
else:
return _("End of %s") % obj.name
3
Example 16
Project: django-newsletter Source File: admin.py
def make_unsubscribed(self, request, queryset):
rows_updated = queryset.update(subscribed=False)
self.message_user(
request,
ungettext(
"%d user has been successfully unsubscribed.",
"%d users have been successfully unsubscribed.",
rows_updated
) % rows_updated
)
3
Example 17
Project: yawd-translations Source File: admin.py
def delete_selected_lang(self, request, queryset):
"""
This delete action will ensure that the default language will not
be deleted.
"""
queryset = queryset.exclude(default=True)
count = queryset.count()
queryset.delete()
self.message_user(request, ungettext(
'%(count)d non-default language was deleted',
'%(count)d non-default languages were deleted',
count) % {
'count': count,
})
3
Example 18
Project: feincms-elephantblog Source File: blogping.py
@staticmethod
def _entry_admin_update_fn(new_state, new_state_dict,
short_description=None):
def _fn(modeladmin, request, queryset):
rows_updated = queryset.update(**new_state_dict)
modeladmin.message_user(request, ungettext(
'One entry was successfully marked as %(state)s',
'%(count)s entries were successfully marked as %(state)s',
rows_updated) % {'state': new_state, 'count': rows_updated})
if short_description:
_fn.short_description = short_description
return _fn
3
Example 19
Project: PyClassLessons Source File: forms.py
def clean_comment(self):
"""
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
contain anything in PROFANITIES_LIST.
"""
comment = self.cleaned_data["comment"]
if settings.COMMENTS_ALLOW_PROFANITIES == False:
bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
if bad_words:
raise forms.ValidationError(ungettext(
"Watch your mouth! The word %s is not allowed here.",
"Watch your mouth! The words %s are not allowed here.",
len(bad_words)) % get_text_list(
['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1])
for i in bad_words], ugettext('and')))
return comment
3
Example 20
def approve_permissions(self, request, queryset):
for permission in queryset:
permission.approve(request.user)
message = ungettext(
"%(count)d permission successfully approved.",
"%(count)d permissions successfully approved.", len(queryset))
self.message_user(request, message % {'count': len(queryset)})
3
Example 21
Project: veyepar Source File: admin.py
def bump_state(self, request, queryset):
rows_updated = 0
for obj in queryset:
obj.state += 1
obj.save()
rows_updated +=1
msg = ungettext(
'bumpped state in %(count)d %(name)s successfully.',
'bumpped state in %(count)d %(name_plural)s successfully.',
rows_updated
) % {
'count': rows_updated,
'name': self.model._meta.verbose_name.title(),
'name_plural': self.model._meta.verbose_name_plural.title()
}
messages.success(request, msg)
3
Example 22
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 ungettext(singular, plural, n or 0)
3
Example 23
Project: Misago Source File: poll.py
def validate_choices_num(self, choices):
total_choices = len(choices)
if total_choices < 2:
raise serializers.ValidationError(_("You need to add at least two choices to a poll."))
if total_choices > MAX_POLL_OPTIONS:
message = ungettext(
"You can't add more than %(limit_value)s option to a single poll (added %(show_value)s).",
"You can't add more than %(limit_value)s options to a single poll (added %(show_value)s).",
MAX_POLL_OPTIONS)
raise serializers.ValidationError(message % {
'limit_value': MAX_POLL_OPTIONS,
'show_value': total_choices
})
3
Example 24
def _bulk_flag(self, request, queryset, action, done_message):
"""
Flag, approve, or remove some comments from an admin action. Actually
calls the `action` argument to perform the heavy lifting.
"""
n_comments = 0
for comment in queryset:
action(request, comment)
n_comments += 1
msg = ungettext(u'1 comment was successfully %(action)s.',
u'%(count)s comments were successfully %(action)s.',
n_comments)
self.message_user(request, msg % {'count': n_comments, 'action': done_message(n_comments)})
3
Example 25
def get_error_message(self):
"""
Returns this validator's error message.
"""
msg = ungettext("The new password must contain %d or more number.",
"The new password must contain %d or more numbers.",
self.get_min_count()) % self.get_min_count()
return msg
3
Example 26
def _bulk_flag(self, request, queryset, action, done_message):
"""
Flag, approve, or remove some comments from an admin action. Actually
calls the `action` argument to perform the heavy lifting.
"""
n_comments = 0
for comment in queryset:
action(request, comment)
n_comments += 1
msg = ungettext('%(count)s comment was successfully %(action)s.',
'%(count)s comments were successfully %(action)s.',
n_comments)
self.message_user(request, msg % {'count': n_comments, 'action': done_message(n_comments)})
3
Example 27
def clean(self):
cleaned_data = super(MessageCreateForm, self).clean()
if not self.writeitinstance.config.allow_messages_using_form:
raise ValidationError("")
if len(cleaned_data['persons']) > self.writeitinstance.config.maximum_recipients:
error_messages = ungettext(
'You can send messages to at most %(count)d person',
'You can send messages to at most %(count)d people',
self.writeitinstance.config.maximum_recipients) % {
'count': self.writeitinstance.config.maximum_recipients,
}
raise ValidationError(error_messages)
return cleaned_data
3
Example 28
Project: modoboa Source File: alias.py
@login_required
@permission_required("admin.delete_alias")
def delalias(request):
selection = request.GET["selection"].split(",")
for alid in selection:
alias = Alias.objects.get(pk=alid)
if not request.user.can_access(alias):
raise PermDeniedException
alias.delete()
msg = ungettext("Alias deleted", "Aliases deleted", len(selection))
return render_to_json_response(msg)
3
Example 29
def archive(self, request, notifications):
for notification in notifications:
notification.archive()
msg = ungettext(
'%(count)d notification archived',
'%(count)d notifications archived', len(notifications)) \
% {'count': len(notifications)}
messages.success(request, msg)
return self.get_success_response()
3
Example 30
def __str__(self):
if self.min_duration == self.max_duration:
days = self.max_duration.days
return ungettext("%s day", "%s days", days) % (days,)
return _("%(min)s--%(max)s days") % {
"min": self.min_duration.days, "max": self.max_duration.days}
3
Example 31
def get_upsell_message(self, offer, basket):
num_matches = self._get_num_matches(basket)
delta = self.value - num_matches
return ungettext('Buy %(delta)d more product from %(range)s',
'Buy %(delta)d more products from %(range)s', delta) \
% {'delta': delta, 'range': self.range}
3
Example 32
Project: modoboa Source File: identity.py
@login_required
@permission_required("core.delete_user")
def delaccount(request, pk):
keepdir = True if request.POST.get("keepdir", "false") == "true" else False
User.objects.get(pk=pk).delete(request.user, keep_mb_dir=keepdir)
return render_to_json_response(
ungettext("Account deleted", "Accounts deleted", 1)
)
3
Example 33
Project: site Source File: admin.py
def recalculate_points(self, request, queryset):
count = 0
for participation in queryset:
participation.recalculate_score()
count += 1
self.message_user(request, ungettext('%d participation have scores recalculated.',
'%d participations have scores recalculated.',
count) % count)
3
Example 34
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 ungettext(singular, plural, n or 0)
3
Example 35
Project: django-newsletter Source File: admin.py
def make_subscribed(self, request, queryset):
rows_updated = queryset.update(subscribed=True)
self.message_user(
request,
ungettext(
"%d user has been successfully subscribed.",
"%d users have been successfully subscribed.",
rows_updated
) % rows_updated
)
3
Example 36
@hooks.register('describe_collection_contents')
def describe_collection_docs(collection):
images_count = get_image_model().objects.filter(collection=collection).count()
if images_count:
url = urlresolvers.reverse('wagtailimages:index') + ('?collection_id=%d' % collection.id)
return {
'count': images_count,
'count_text': ungettext(
"%(count)s image",
"%(count)s images",
images_count
) % {'count': images_count},
'url': url,
}
3
Example 37
def validate(self, password, user=None):
if len(password) < self.min_length:
raise ValidationError(
ungettext(
"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},
)
3
Example 38
def get_context(self, context):
if self.actions and self.admin_view.result_count:
av = self.admin_view
selection_note_all = ungettext('%(total_count)s selected',
'All %(total_count)s selected', av.result_count)
new_context = {
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(av.result_list)},
'selection_note_all': selection_note_all % {'total_count': av.result_count},
'action_choices': self.get_action_choices(),
'actions_selection_counter': self.actions_selection_counter,
}
context.update(new_context)
return context
3
Example 39
def get_short_description(self):
instance = self.get_plugin_instance()[0]
if not instance:
return ugettext("<Empty>")
column_count = len(self.child_plugin_instances or [])
column_count_str = ungettext(
"1 item",
"%(count)i items",
column_count
) % {'count': column_count}
return column_count_str
3
Example 40
Project: veyepar Source File: admin.py
def set_stopped(self, request, queryset):
rows_updated = queryset.update(stop=True)
msg = ungettext(
'Set stopped to true in %(count)d %(name)s successfully.',
'Set stopped to true in %(count)d %(name_plural)s successfully.',
rows_updated
) % {
'count': rows_updated,
'name': self.model._meta.verbose_name.title(),
'name_plural': self.model._meta.verbose_name_plural.title()
}
messages.success(request, msg)
3
Example 41
@property
def nav_subtitle(self):
calls = len(self.calls)
duration = int(sum(((c['end'] - c['start']) for c in self.calls)) * 1000)
return ungettext('%(calls)d call in %(duration).2fms',
'%(calls)d calls in %(duration).2fms',
calls) % {'calls': calls, 'duration': duration}
3
Example 42
def filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except TypeError:
return u"0 bytes"
if bytes < 1024:
return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
if bytes < 1024 * 1024:
return ugettext("%.1f KB") % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return ugettext("%.1f MB") % (bytes / (1024 * 1024))
return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
3
Example 43
Project: django-admin2 Source File: actions.py
def post(self, request):
if self.process_queryset() is None:
# objects_name should already be pluralized, see __init__
message = ungettext(
self.success_message,
self.success_message_plural,
self.item_count
) % {
'count': self.item_count, 'items': self.objects_name
}
messages.add_message(request, messages.INFO, message)
return None
3
Example 44
Project: veyepar Source File: admin.py
def re_slug(self, request, queryset):
rows_updated = 0
for obj in queryset:
# obj.slug = fnify(obj.name)
obj.slug = "" ## blank slug, .save will gen a slug.
obj.save()
rows_updated +=1
msg = ungettext(
'updated slug with fnify(name) in %(count)d %(name)s successfully.',
'updated slug with fnify(name) in %(count)d %(name_plural)s successfully.',
rows_updated
) % {
'count': rows_updated,
'name': self.model._meta.verbose_name.title(),
'name_plural': self.model._meta.verbose_name_plural.title()
}
messages.success(request, msg)
3
Example 45
def __call__(self, value):
if not self.get_max_count():
return
consecutive_found = False
for _, group in itertools.groupby(force_text(value)):
if len(list(group)) > self.get_max_count():
consecutive_found = True
if consecutive_found:
msg = ungettext("The new password contains consecutive"
" characters. Only %(count)d consecutive character"
" is allowed.",
"The new password contains consecutive"
" characters. Only %(count)d consecutive characters"
" are allowed.",
self.get_max_count()) % {'count': self.get_max_count()}
raise ValidationError(msg, code=self.code)
3
Example 46
def intword(value):
"""
Converts a large integer to a friendly text representation. Works best for
numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000
becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
"""
value = int(value)
if value < 1000000:
return value
if value < 1000000000:
new_value = value / 1000000.0
return ungettext('%(value).1f million', '%(value).1f million', new_value) % {'value': new_value}
if value < 1000000000000:
new_value = value / 1000000000.0
return ungettext('%(value).1f billion', '%(value).1f billion', new_value) % {'value': new_value}
if value < 1000000000000000:
new_value = value / 1000000000000.0
return ungettext('%(value).1f trillion', '%(value).1f trillion', new_value) % {'value': new_value}
return value
3
Example 47
Project: vumi-go Source File: billing_tags.py
@register.simple_tag
def credit_balance(user):
"""Return the credit balance for the given ``user``'s account.
If the user has multiple accounts, the first one's balance is returned.
"""
account = user.account_set.get()
credits = account.credit_balance
return "%s %s" % (
format_credits(credits),
ungettext("credit", "credits", credits))
3
Example 48
Project: Misago Source File: validators.py
def validate_password(value):
if len(value) < settings.password_length_min:
message = ungettext(
'Valid password must be at least %(limit_value)s character long.',
'Valid password must be at least %(limit_value)s characters long.',
settings.password_length_min)
message = message % {'limit_value': settings.password_length_min}
raise ValidationError(message)
3
Example 49
def __init__(self, wait=None, detail=None, code=None):
if detail is None:
detail = force_text(self.default_detail)
if wait is not None:
wait = math.ceil(wait)
detail = ' '.join((
detail,
force_text(ungettext(self.extra_detail_singular.format(wait=wait),
self.extra_detail_plural.format(wait=wait),
wait))))
self.wait = wait
super(Throttled, self).__init__(detail, code)
3
Example 50
@property
def unit_description(self):
if self.num_excess_users > 0:
return ungettext(
"Per User fee exceeding monthly limit of %(monthly_limit)s user.",
"Per User fee exceeding monthly limit of %(monthly_limit)s users.",
self.rate.monthly_limit
) % {
'monthly_limit': self.rate.monthly_limit,
}