예제 #1
0
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)
예제 #2
0
    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('1 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
0
 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
예제 #4
0
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)
예제 #5
0
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 subclass 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(
                'a second ago', '%(count)s seconds ago', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                'a minute ago', '%(count)s minutes ago', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                '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(
                '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(
                'a minute from now', '%(count)s minutes from now', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                'an hour from now', '%(count)s hours from now', count
            ) % {'count': count}
예제 #6
0
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://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
예제 #7
0
 def render(self, context):
     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)
     # Escape all isolated '%'
     singular = re.sub('%(?!\()', '%%', 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)
         plural = re.sub('%(?!\()', '%%', plural)
         if message_context:
             result = translation.npgettext(message_context, singular,
                                            plural, count)
         else:
             result = translation.ungettext(singular, plural, count)
         vars.extend(plural_vars)
     else:
         if message_context:
             result = translation.pgettext(message_context, singular)
         else:
             result = translation.ugettext(singular)
     data = dict([(v, _render_value_in_context(context.get(v, ''), context)) for v in vars])
     context.pop()
     try:
         result = result % data
     except (KeyError, ValueError):
         with translation.override(None):
             result = self.render(context)
     return result
예제 #8
0
                value = int(value)
        except (TypeError, ValueError):
            return intcomma(value, False)
        else:
            return number_format(value, force_grouping=True)
    orig = force_text(value)
    new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
    if orig == new:
        return new
    else:
        return intcomma(new, use_l10n)

# A tuple of standard large number to their converters
intword_converters = (
    (6, lambda number: (
        ungettext('%(value).1f million', '%(value).1f million', number),
        ungettext('%(value)s million', '%(value)s million', number),
    )),
    (9, lambda number: (
        ungettext('%(value).1f billion', '%(value).1f billion', number),
        ungettext('%(value)s billion', '%(value)s billion', number),
    )),
    (12, lambda number: (
        ungettext('%(value).1f trillion', '%(value).1f trillion', number),
        ungettext('%(value)s trillion', '%(value)s trillion', number),
    )),
    (15, lambda number: (
        ungettext('%(value).1f quadrillion', '%(value).1f quadrillion', number),
        ungettext('%(value)s quadrillion', '%(value)s quadrillion', number),
    )),
    (18, lambda number: (
예제 #9
0
 def remove_comments(self, request, queryset):
     self._bulk_flag(request, queryset, perform_delete,
                     lambda n: ungettext('removed', 'removed', n))
예제 #10
0
 def approve_comments(self, request, queryset):
     self._bulk_flag(request, queryset, perform_approve,
                     lambda n: ungettext('approved', 'approved', n))
예제 #11
0
 def flag_comments(self, request, queryset):
     self._bulk_flag(request, queryset, perform_flag,
                     lambda n: ungettext('flagged', 'flagged', n))