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)
Example #2
0
 def clean_url(self):
     url = self.cleaned_data['url']
     if not url.startswith('/'):
         raise forms.ValidationError(ugettext("URL is missing a leading slash."))
     if (settings.APPEND_SLASH and
         'djangocg.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES and
         not url.endswith('/')):
         raise forms.ValidationError(ugettext("URL is missing a trailing slash."))
     return url
Example #3
0
    def __init__(
        self,
        request,
        model,
        list_display,
        list_display_links,
        list_filter,
        date_hierarchy,
        search_fields,
        list_select_related,
        list_per_page,
        list_max_show_all,
        list_editable,
        model_admin,
    ):
        self.model = model
        self.opts = model._meta
        self.lookup_opts = self.opts
        self.root_query_set = model_admin.queryset(request)
        self.list_display = list_display
        self.list_display_links = list_display_links
        self.list_filter = list_filter
        self.date_hierarchy = date_hierarchy
        self.search_fields = search_fields
        self.list_select_related = list_select_related
        self.list_per_page = list_per_page
        self.list_max_show_all = list_max_show_all
        self.model_admin = model_admin

        # Get search parameters from the query string.
        try:
            self.page_num = int(request.GET.get(PAGE_VAR, 0))
        except ValueError:
            self.page_num = 0
        self.show_all = ALL_VAR in request.GET
        self.is_popup = IS_POPUP_VAR in request.GET
        self.to_field = request.GET.get(TO_FIELD_VAR)
        self.params = dict(request.GET.items())
        if PAGE_VAR in self.params:
            del self.params[PAGE_VAR]
        if ERROR_FLAG in self.params:
            del self.params[ERROR_FLAG]

        if self.is_popup:
            self.list_editable = ()
        else:
            self.list_editable = list_editable
        self.query = request.GET.get(SEARCH_VAR, "")
        self.query_set = self.get_query_set(request)
        self.get_results(request)
        if self.is_popup:
            title = ugettext("Select %s")
        else:
            title = ugettext("Select %s to change")
        self.title = title % force_text(self.opts.verbose_name)
        self.pk_attname = self.lookup_opts.pk.attname
Example #4
0
 def get_unique_error_message(self, unique_check):
     if len(unique_check) == 1:
         return ugettext("Please correct the duplicate data for %(field)s.") % {
             "field": unique_check[0],
         }
     else:
         return ugettext("Please correct the duplicate data for %(field)s, "
             "which must be unique.") % {
                 "field": get_text_list(unique_check, six.text_type(_("and"))),
             }
Example #5
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
Example #6
0
 def get_date_error_message(self, date_check):
     return ugettext("Please correct the duplicate data for %(field_name)s "
         "which must be unique for the %(lookup)s in %(date_field)s.") % {
         'field_name': date_check[2],
         'date_field': date_check[3],
         'lookup': six.text_type(date_check[1]),
     }
def yesno(value, arg=None):
    """
    Given a string mapping values for true, false and (optionally) None,
    returns one of those strings according to the value:

    ==========  ======================  ==================================
    Value       Argument                Outputs
    ==========  ======================  ==================================
    ``True``    ``"yeah,no,maybe"``     ``yeah``
    ``False``   ``"yeah,no,maybe"``     ``no``
    ``None``    ``"yeah,no,maybe"``     ``maybe``
    ``None``    ``"yeah,no"``           ``"no"`` (converts None to False
                                        if no mapping for None is given.
    ==========  ======================  ==================================
    """
    if arg is None:
        arg = ugettext('yes,no,maybe')
    bits = arg.split(',')
    if len(bits) < 2:
        return value # Invalid arg.
    try:
        yes, no, maybe = bits
    except ValueError:
        # Unpack list of wrong size (no "maybe" value provided).
        yes, no, maybe = bits[0], bits[1], bits[1]
    if value is None:
        return maybe
    if value:
        return yes
    return no
Example #8
0
    def test_flatpage_nosites(self):
        data = dict(url='/myflatpage1/', **self.form_data)
        data.update({'sites': ''})

        f = FlatpageForm(data=data)

        self.assertFalse(f.is_valid())

        self.assertEqual(
            f.errors,
            {'sites': [translation.ugettext('This field is required.')]})
Example #9
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
Example #10
0
    def render(self, name, value, attrs):
        encoded = value

        if not is_password_usable(encoded):
            return "None"

        final_attrs = self.build_attrs(attrs)

        try:
            hasher = identify_hasher(encoded)
        except ValueError:
            summary = mark_safe("<strong>Invalid password format or unknown hashing algorithm.</strong>")
        else:
            summary = format_html_join('',
                                       "<strong>{0}</strong>: {1} ",
                                       ((ugettext(key), value)
                                        for key, value in hasher.safe_summary(encoded).items())
                                       )

        return format_html("<div{0}>{1}</div>", flatatt(final_attrs), summary)
Example #11
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
Example #12
0
    def user_change_password(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.queryset(request), pk=id)
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                msg = ugettext('Password changed successfully.')
                messages.success(request, msg)
                return HttpResponseRedirect('..')
        else:
            form = self.change_password_form(user)

        fieldsets = [(None, {'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title': _('Change password: %s') % escape(user.username),
            'adminForm': adminForm,
            'form_url': form_url,
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
        }
        return TemplateResponse(request, [
            self.change_user_password_template or
            'admin/auth/user/change_password.html'
        ], context, current_app=self.admin_site.name)
Example #13
0
 def get_form_error(self):
     return ugettext("Please correct the duplicate values below.")
Example #14
0
 def render(self, context):
     from djangocg.conf import settings
     context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES]
     return ''