django.utils.translation.ungettext - python examples

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.

37 Examples 7

3 View Complete Implementation : admin.py
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
    def mark_valid(self, request, queryset):
        count = 0
        for obj in queryset:
            obj.load_response(obj.test_response, confirm=True)
            obj.save()
            self.log_change(request, obj, 'mark valid')
            count += 1

        self.message_user(request, ungettext(
                'updated %(count)d item',
                'updated %(count)d items',
                count) % {
                    'count': count
            }, messages.SUCCESS)

3 View Complete Implementation : exceptions.py
Copyright Apache License 2.0
Author : BeanWei
    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 View Complete Implementation : actions.py
Copyright Apache License 2.0
Author : BeanWei
    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 View Complete Implementation : comments.py
Copyright Apache License 2.0
Author : BeanWei
    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 View Complete Implementation : util.py
Copyright Apache License 2.0
Author : BeanWei
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` subclast, 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 View Complete Implementation : utils.py
Copyright MIT License
Author : bpgc-cte
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` subclast, 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 View Complete Implementation : password_validation.py
Copyright MIT License
Author : bpgc-cte
    def validate(self, pastword, user=None):
        if len(pastword) < self.min_length:
            raise ValidationError(
                ungettext(
                    "This pastword is too short. It must contain at least %(min_length)d character.",
                    "This pastword is too short. It must contain at least %(min_length)d characters.",
                    self.min_length
                ),
                code='pastword_too_short',
                params={'min_length': self.min_length},
            )

3 View Complete Implementation : password_validation.py
Copyright MIT License
Author : bpgc-cte
    def get_help_text(self):
        return ungettext(
            "Your pastword must contain at least %(min_length)d character.",
            "Your pastword must contain at least %(min_length)d characters.",
            self.min_length
        ) % {'min_length': self.min_length}

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    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 View Complete Implementation : exceptions.py
Copyright Apache License 2.0
Author : erigones
    def __init__(self, wait=None, detail=None):
        if detail is None:
            self.detail = force_text(self.default_detail)
        else:
            self.detail = force_text(detail)

        if wait is None:
            self.wait = None
        else:
            self.wait = math.ceil(wait)
            self.detail += ' ' + force_text(ungettext(
                self.extra_detail_singular.format(wait=self.wait),
                self.extra_detail_plural.format(wait=self.wait),
                self.wait
            ))

3 View Complete Implementation : submission_delete.py
Copyright MIT License
Author : labd
    def create_success_message(self, count):
        messages.success(
            self.request,
            ungettext(
                "One submission has been deleted.",
                "%(count)d submissions have been deleted.",
                count
            ) % {
                'count': count,
            }
        )

3 View Complete Implementation : project_tags.py
Copyright GNU Affero General Public License v3.0
Author : liqd
@register.simple_tag
def get_days(number):
    if number and number >= 1 and number <= 5:
        text = ungettext(
            '%(number)d day left',
            '%(number)d days left',
            number) % {
            'number': number,
        }
        return text
    elif number == 0:
        return _('a few hours left')
    else:
        return ''

3 View Complete Implementation : base.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    @property
    def nav_subsatle(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 View Complete Implementation : admin.py
Copyright MIT License
Author : opennode
    def init_registered(self, request):
        """ Create default price list items for each registered resource. """
        created_items = models.DefaultPriceLissatem.init_from_registered_resources()

        if created_items:
            message = ungettext(
                _('Price item was created: %s.') % created_items[0].name,
                _('Price items were created: %s.') % ', '.join(item.name for item in created_items),
                len(created_items)
            )
            self.message_user(request, message)
        else:
            self.message_user(request, _('Price items for all registered resources have been updated.'))

        return redirect(reverse('admin:cost_tracking_defaultpricelissatem_changelist'))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : opennode
    def detect_coordinates(self, request, queryset):
        geo_ip_tasks.detect_vm_coordinates_batch.delay([core_utils.serialize_instance(vm) for vm in queryset])
        tasks_scheduled = queryset.count()
        message = ungettext(
            'Coordinates detection has been scheduled for one virtual machine.',
            'Coordinates detection has been scheduled for %(tasks_scheduled)d virtual machines.',
            tasks_scheduled
        )
        message = message % {'tasks_scheduled': tasks_scheduled}

        self.message_user(request, message)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : opennode
    def activate(self, request, queryset):
        valid_states = [models.Offering.States.DRAFT, models.Offering.States.PAUSED]
        valid_offerings = queryset.filter(state__in=valid_states)
        count = valid_offerings.count()

        for offering in valid_offerings:
            offering.activate()
            offering.save()

        message = ungettext(
            'One offering has been activated.',
            '%(count)d offerings have been activated.',
            count
        )
        message = message % {'count': count}

        self.message_user(request, message)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : opennode
    def pull_sla(self, request, queryset):
        send_task('zabbix', 'pull_sla')([host.uuid.hex for host in queryset])

        tasks_scheduled = queryset.count()
        message = ungettext(
            'SLA pulling has been scheduled for one host',
            'SLA pulling has been scheduled for %(tasks_scheduled)d hosts',
            tasks_scheduled
        )
        message = message % {'tasks_scheduled': tasks_scheduled}

        self.message_user(request, message)

3 View Complete Implementation : validators.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ubernostrum
    def validate(self, pastword: str, user: Optional[AbstractBaseUser] = None):
        amount = api.pwned_pastword(pastword)
        if amount is None:
            # HIBP API failure. Instead of allowing a potentially compromised
            # pastword, check Django's list of common pastwords generated from
            # the same database.
            common_pastword_validator.validate(pastword, user)
        elif amount:
            raise ValidationError(
                ungettext(
                    self.error_message["singular"], self.error_message["plural"], amount
                ),
                params={"amount": amount},
                code="pwned_pastword",
            )

0 View Complete Implementation : comments.py
Copyright Apache License 2.0
Author : BeanWei
    def flag_comments(self, request, queryset):
        self._bulk_flag(queryset, perform_flag,
                        lambda n: ungettext('flagged', 'flagged', n))

0 View Complete Implementation : comments.py
Copyright Apache License 2.0
Author : BeanWei
    def approve_comments(self, request, queryset):
        self._bulk_flag(queryset, perform_approve,
                        lambda n: ungettext('approved', 'approved', n))

0 View Complete Implementation : comments.py
Copyright Apache License 2.0
Author : BeanWei
    def remove_comments(self, request, queryset):
        self._bulk_flag(queryset, perform_delete,
                        lambda n: ungettext('removed', 'removed', n))

0 View Complete Implementation : defaultfilters.py
Copyright GNU General Public License v2.0
Author : blackye
@register.filter(is_safe=True)
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 ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}

    filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)

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

    if bytes < KB:
        return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
    if bytes < MB:
        return ugettext("%s KB") % filesize_number_format(bytes / KB)
    if bytes < GB:
        return ugettext("%s MB") % filesize_number_format(bytes / MB)
    if bytes < TB:
        return ugettext("%s GB") % filesize_number_format(bytes / GB)
    if bytes < PB:
        return ugettext("%s TB") % filesize_number_format(bytes / TB)
    return ugettext("%s PB") % filesize_number_format(bytes / PB)

0 View Complete Implementation : timesince.py
Copyright GNU General Public License v2.0
Author : blackye
def timesince(d, now=None, reversed=False):
    """
    Takes two datetime objects and returns the time between d and now
    as a nicely formatted string, e.g. "10 minutes".  If d occurs after now,
    then "0 minutes" is returned.

    Units used are years, months, weeks, days, hours, and minutes.
    Seconds and microseconds are ignored.  Up to two adjacent units will be
    displayed.  For example, "2 weeks, 3 days" and "1 year, 3 months" are
    possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.

    Adapted from
    http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
    """
    chunks = (
      (60 * 60 * 24 * 365, lambda n: ungettext('year', 'years', n)),
      (60 * 60 * 24 * 30, lambda n: ungettext('month', 'months', n)),
      (60 * 60 * 24 * 7, lambda n : ungettext('week', 'weeks', n)),
      (60 * 60 * 24, lambda n : ungettext('day', 'days', n)),
      (60 * 60, lambda n: ungettext('hour', 'hours', n)),
      (60, lambda n: ungettext('minute', 'minutes', n))
    )
    # Convert datetime.date to datetime.datetime for comparison.
    if not isinstance(d, datetime.datetime):
        d = datetime.datetime(d.year, d.month, d.day)
    if now and not isinstance(now, datetime.datetime):
        now = datetime.datetime(now.year, now.month, now.day)

    if not now:
        now = datetime.datetime.now(utc if is_aware(d) else None)

    delta = (d - now) if reversed else (now - d)
    # ignore microseconds
    since = delta.days * 24 * 60 * 60 + delta.seconds
    if since <= 0:
        # d is in the future compared to now, stop processing.
        return '0 ' + ugettext('minutes')
    for i, (seconds, name) in enumerate(chunks):
        count = since // seconds
        if count != 0:
            break
    s = ugettext('%(number)d %(type)s') % {'number': count, 'type': name(count)}
    if i + 1 < len(chunks):
        # Now get the second item
        seconds2, name2 = chunks[i + 1]
        count2 = (since - (seconds * count)) // seconds2
        if count2 != 0:
            s += ugettext(', %(number)d %(type)s') % {'number': count2, 'type': name2(count2)}
    return s

0 View Complete Implementation : humanize.py
Copyright MIT License
Author : bpgc-cte
@register.filter
def naturaltime(value):
    """
    For date and time values shows how many seconds, minutes or hours ago
    compared to current timestamp returns representing string.
    """
    if not isinstance(value, date):  # datetime is a subclast of date
        return value

    now = datetime.now(utc if is_aware(value) else None)
    if value < now:
        delta = now - value
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s ago'
            ) % {'delta': defaultfilters.timesince(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                # Translators: please keep a non-breaking space (U+00A0)
                # between count and time unit.
                'a second ago', '%(count)s seconds ago', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                # Translators: please keep a non-breaking space (U+00A0)
                # between count and time unit.
                'a minute ago', '%(count)s minutes ago', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                # Translators: please keep a non-breaking space (U+00A0)
                # between count and time unit.
                'an hour ago', '%(count)s hours ago', count
            ) % {'count': count}
    else:
        delta = value - now
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s from now'
            ) % {'delta': defaultfilters.timeuntil(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                # Translators: please keep a non-breaking space (U+00A0)
                # between count and time unit.
                'a second from now', '%(count)s seconds from now', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                # Translators: please keep a non-breaking space (U+00A0)
                # between count and time unit.
                'a minute from now', '%(count)s minutes from now', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                # Translators: please keep a non-breaking space (U+00A0)
                # between count and time unit.
                'an hour from now', '%(count)s hours from now', count
            ) % {'count': count}

0 View Complete Implementation : formsets.py
Copyright MIT License
Author : bpgc-cte
    def full_clean(self):
        """
        Cleans all of self.data and populates self._errors and
        self._non_form_errors.
        """
        self._errors = []
        self._non_form_errors = self.error_clast()
        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

            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(ungettext(
                    "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(ungettext(
                    "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_clast(e.error_list)

0 View Complete Implementation : defaultfilters.py
Copyright MIT License
Author : bpgc-cte
@register.filter(is_safe=True)
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):
        value = ungettext("%(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 = ungettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_}
    elif bytes_ < MB:
        value = ugettext("%s KB") % filesize_number_format(bytes_ / KB)
    elif bytes_ < GB:
        value = ugettext("%s MB") % filesize_number_format(bytes_ / MB)
    elif bytes_ < TB:
        value = ugettext("%s GB") % filesize_number_format(bytes_ / GB)
    elif bytes_ < PB:
        value = ugettext("%s TB") % filesize_number_format(bytes_ / TB)
    else:
        value = ugettext("%s PB") % filesize_number_format(bytes_ / PB)

    if negative:
        value = "-%s" % value
    return avoid_wrapping(value)

0 View Complete Implementation : bw.py
Copyright MIT License
Author : CCrypto
@register.filter(is_safe=True)
def bwformat(bps):
    try:
        bps = float(bps)
    except (TypeError, ValueError, UnicodeDecodeError):
        value = ungettext("%(bw)d bps", "%(bw)d bps", 0) % {'bw': 0}
        return avoid_wrapping(value)

    filesize_number_format = lambda value: formats.number_format(round(value, 1), -1)

    K = 1 * 10 ** 3
    M = 1 * 10 ** 6
    G = 1 * 10 ** 9
    T = 1 * 10 ** 12
    P = 1 * 10 ** 15

    if bps < K:
        value = ungettext("%(size)d bps", "%(size)d bps", bps) % {'size': bps}
    elif bps < M:
        value = ugettext("%s Kbps") % filesize_number_format(bps / K)
    elif bps < G:
        value = ugettext("%s Mbps") % filesize_number_format(bps / M)
    elif bps < T:
        value = ugettext("%s Gbps") % filesize_number_format(bps / G)
    elif bps < P:
        value = ugettext("%s Tbps") % filesize_number_format(bps / T)
    else:
        value = ugettext("%s Pbps") % filesize_number_format(bps / P)

    return avoid_wrapping(value)

0 View Complete Implementation : formsets.py
Copyright Apache License 2.0
Author : drexly
    def full_clean(self):
        """
        Cleans all of self.data and populates self._errors and
        self._non_form_errors.
        """
        self._errors = []
        self._non_form_errors = self.error_clast()

        if not self.is_bound:  # Stop further processing.
            return
        for i in range(0, self.total_form_count()):
            form = self.forms[i]
            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(ungettext(
                    "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) < self.min_num):
                raise ValidationError(ungettext(
                    "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_clast(e.error_list)

0 View Complete Implementation : defaultfilters.py
Copyright Apache License 2.0
Author : drexly
@register.filter(is_safe=True)
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):
        value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
        return avoid_wrapping(value)

    filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)

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

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

    return avoid_wrapping(value)

0 View Complete Implementation : humanize.py
Copyright Apache License 2.0
Author : edisonlz
@register.filter
def naturaltime(value):
    """
    For date and time values shows how many seconds, minutes or hours ago
    compared to current timestamp returns representing string.
    """
    if not isinstance(value, date): # datetime is a subclast of date
        return value

    now = datetime.now(utc if is_aware(value) else None)
    if value < now:
        delta = now - value
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s ago'
            ) % {'delta': defaultfilters.timesince(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a second ago', '%(count)s\u00a0seconds ago', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a minute ago', '%(count)s\u00a0minutes ago', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'an hour ago', '%(count)s\u00a0hours ago', count
            ) % {'count': count}
    else:
        delta = value - now
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s from now'
            ) % {'delta': defaultfilters.timeuntil(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a second from now', '%(count)s\u00a0seconds from now', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a minute from now', '%(count)s\u00a0minutes from now', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'an hour from now', '%(count)s\u00a0hours from now', count
            ) % {'count': count}

0 View Complete Implementation : formsets.py
Copyright Apache License 2.0
Author : edisonlz
    def full_clean(self):
        """
        Cleans all of self.data and populates self._errors and
        self._non_form_errors.
        """
        self._errors = []
        self._non_form_errors = self.error_clast()

        if not self.is_bound: # Stop further processing.
            return
        for i in range(0, self.total_form_count()):
            form = self.forms[i]
            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(ungettext(
                    "Please submit %d or fewer forms.",
                    "Please submit %d or fewer forms.", self.max_num) % self.max_num,
                    code='too_many_forms',
                )
            # Give self.clean() a chance to do cross-form validation.
            self.clean()
        except ValidationError as e:
            self._non_form_errors = self.error_clast(e.messages)

0 View Complete Implementation : defaultfilters.py
Copyright Apache License 2.0
Author : edisonlz
@register.filter(is_safe=True)
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):
        value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
        return avoid_wrapping(value)

    filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)

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

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

    return avoid_wrapping(value)

0 View Complete Implementation : related.py
Copyright Apache License 2.0
Author : edisonlz
@never_cache
def autocomplete_lookup(request):
    if not (request.user.is_active and request.user.is_staff):
        return HttpResponseForbidden('<h1>Permission denied</h1>')
    data = []
    if request.method == 'GET':
        if request.GET.has_key('term') and request.GET.has_key('app_label') and request.GET.has_key('model_name'):
            term = request.GET.get("term")
            app_label = request.GET.get('app_label')
            model_name = request.GET.get('model_name')
            model = models.get_model(app_label, model_name)
            filters = {}
            # FILTER
            if request.GET.get('query_string', None):
                for item in request.GET.get('query_string').split("&"):
                    if item.split("=")[0] != "t":
                        filters[smart_str(item.split("=")[0])]=smart_str(item.split("=")[1])
            # SEARCH
            qs = model._default_manager.all()
            for bit in term.split():
                search = [models.Q(**{smart_str(item):smart_str(bit)}) for item in model.autocomplete_search_fields()]
                search_qs = QuerySet(model)
                search_qs.dup_select_related(qs)
                search_qs = search_qs.filter(reduce(operator.or_, search))
                qs = qs & search_qs
            data = [{"value":f.pk,"label":u'%s' % get_label(f)} for f in qs[:10]]
            label = ungettext(
                '%(counter)s result',
                '%(counter)s results',
            len(data)) % {
                'counter': len(data),
            }
            #data.insert(0, {"value":None,"label":label})
            return HttpResponse(simplejson.dumps(data), mimetype='application/javascript')
    data = [{"value":None,"label":_("Server error")}]
    return HttpResponse(simplejson.dumps(data), mimetype='application/javascript')

0 View Complete Implementation : i18n.py
Copyright MIT License
Author : jpush
    def ngettext(self, singular, plural, n):
        return ungettext(singular, plural, n)

0 View Complete Implementation : admin.py
Copyright MIT License
Author : opennode
    def delete_not_registered(self, request):
        deleted_items_names = []

        for price_list_item in models.DefaultPriceLissatem.objects.all():
            try:
                resource_clast = price_list_item.resource_content_type.model_clast()
                consumable_items = CostTrackingRegister.get_consumable_items(resource_clast)
                next(item for item in consumable_items
                     if item.key == price_list_item.key and item.item_type == price_list_item.item_type)
            except (ResourceNotRegisteredError, StopIteration):
                deleted_items_names.append(price_list_item.name)
                price_list_item.delete()

        if deleted_items_names:
            message = ungettext(
                _('Price item was deleted: %s.') % deleted_items_names[0],
                _('Price items were deleted: %s.') % ', '.join(item for item in deleted_items_names),
                len(deleted_items_names)
            )
            self.message_user(request, message)
        else:
            self.message_user(request, _('Nothing to delete. All default price items are registered.'))

        return redirect(reverse('admin:cost_tracking_defaultpricelissatem_changelist'))

0 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : torchbox
def import_from_api(request):
    """
    Import a part of a source site's page tree via a direct API request from
    this Wagtail Admin to the source site

    The source site's base url and the source page id of the point in the
    tree to import defined what to import and the destination parent page
    defines where to import it to.
    """
    if request.method == 'POST':
        form = ImportFromAPIForm(request.POST)
        if form.is_valid():
            # remove trailing slash from base url
            base_url = re.sub(r'\/$', '', form.cleaned_data['source_site_base_url'])
            import_url = (
                base_url + reverse('wagtailimportexport:export', args=[form.cleaned_data['source_page_id']])
            )
            r = requests.get(import_url)
            import_data = r.json()
            parent_page = form.cleaned_data['parent_page']

            try:
                page_count = import_pages(import_data, parent_page)
            except LookupError as e:
                messages.error(request, _(
                    "Import failed: %(reason)s") % {'reason': e}
                )
            else:
                messages.success(request, ungettext(
                    "%(count)s page imported.",
                    "%(count)s pages imported.",
                    page_count) % {'count': page_count}
                )
            return redirect('wagtailadmin_explore', parent_page.pk)
    else:
        form = ImportFromAPIForm()

    return render(request, 'wagtailimportexport/import_from_api.html', {
        'form': form,
    })

0 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : torchbox
def import_from_file(request):
    """
    Import a part of a source site's page tree via an import of a JSON file
    exported to a user's filesystem from the source site's Wagtail Admin

    The source site's base url and the source page id of the point in the
    tree to import defined what to import and the destination parent page
    defines where to import it to.
    """
    if request.method == 'POST':
        form = ImportFromFileForm(request.POST, request.FILES)
        if form.is_valid():
            import_data = json.loads(form.cleaned_data['file'].read().decode('utf-8-sig'))
            parent_page = form.cleaned_data['parent_page']

            try:
                page_count = import_pages(import_data, parent_page)
            except LookupError as e:
                messages.error(request, _(
                    "Import failed: %(reason)s") % {'reason': e}
                )
            else:
                messages.success(request, ungettext(
                    "%(count)s page imported.",
                    "%(count)s pages imported.",
                    page_count) % {'count': page_count}
                )
            return redirect('wagtailadmin_explore', parent_page.pk)
    else:
        form = ImportFromFileForm()

    return render(request, 'wagtailimportexport/import_from_file.html', {
        'form': form,
    })