Beispiel #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)

    if bytes < 1024:
        return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {
            'size': bytes
        }
    if bytes < 1024 * 1024:
        return ugettext("%s KB") % filesize_number_format(bytes / 1024)
    if bytes < 1024 * 1024 * 1024:
        return ugettext("%s MB") % filesize_number_format(bytes /
                                                          (1024 * 1024))
    if bytes < 1024 * 1024 * 1024 * 1024:
        return ugettext("%s GB") % filesize_number_format(bytes /
                                                          (1024 * 1024 * 1024))
    if bytes < 1024 * 1024 * 1024 * 1024 * 1024:
        return ugettext("%s TB") % filesize_number_format(
            bytes / (1024 * 1024 * 1024 * 1024))
    return ugettext("%s PB") % filesize_number_format(
        bytes / (1024 * 1024 * 1024 * 1024 * 1024))
Beispiel #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 'my_django.middleware.common.CommonMiddleware'
             in settings.MIDDLEWARE_CLASSES and not url.endswith('/')):
         raise forms.ValidationError(
             ugettext("URL is missing a trailing slash."))
     return url
 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,
                                                    unicode(_("and"))),
                         }
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 u'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
    def render(self, name, value, attrs):
        encoded = value

        if not is_password_usable(encoded):
            return "None"

        final_attrs = self.build_attrs(attrs)

        encoded = smart_str(encoded)

        if len(encoded) == 32 and '$' not in encoded:
            algorithm = 'unsalted_md5'
        else:
            algorithm = encoded.split('$', 1)[0]

        try:
            hasher = get_hasher(algorithm)
        except ValueError:
            summary = "<strong>Invalid password format or unknown hashing algorithm.</strong>"
        else:
            summary = ""
            for key, value in hasher.safe_summary(encoded).iteritems():
                summary += "<strong>%(key)s</strong>: %(value)s " % {"key": ugettext(key), "value": value}

        return mark_safe("<div%(attrs)s>%(summary)s</div>" % {"attrs": flatatt(final_attrs), "summary": summary})
Beispiel #6
0
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(u',')
    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
 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': unicode(date_check[1]),
         }
Beispiel #8
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_unicode(self.opts.verbose_name)
        self.pk_attname = self.lookup_opts.pk.attname
def update_object(request,
                  model=None,
                  object_id=None,
                  slug=None,
                  slug_field='slug',
                  template_name=None,
                  template_loader=loader,
                  extra_context=None,
                  post_save_redirect=None,
                  login_required=False,
                  context_processors=None,
                  template_object_name='object',
                  form_class=None):
    """
    Generic object-update function.

    Templates: ``<app_label>/<model_name>_form.html``
    Context:
        form
            the form for the object
        object
            the original object being edited
    """
    if extra_context is None: extra_context = {}
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    model, form_class = get_model_and_form_class(model, form_class)
    obj = lookup_object(model, object_id, slug, slug_field)

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=obj)
        if form.is_valid():
            obj = form.save()
            msg = ugettext("The %(verbose_name)s was updated successfully.") %\
                                    {"verbose_name": model._meta.verbose_name}
            messages.success(request, msg, fail_silently=True)
            return redirect(post_save_redirect, obj)
    else:
        form = form_class(instance=obj)

    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label,
                                             model._meta.object_name.lower())
    t = template_loader.get_template(template_name)
    c = RequestContext(request, {
        'form': form,
        template_object_name: obj,
    }, context_processors)
    apply_extra_context(extra_context, c)
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, model,
                      getattr(obj, obj._meta.pk.attname))
    return response
def delete_object(request,
                  model,
                  post_delete_redirect,
                  object_id=None,
                  slug=None,
                  slug_field='slug',
                  template_name=None,
                  template_loader=loader,
                  extra_context=None,
                  login_required=False,
                  context_processors=None,
                  template_object_name='object'):
    """
    Generic object-delete function.

    The given template will be used to confirm deletetion if this view is
    fetched using GET; for safty, deletion will only be performed if this
    view is POSTed.

    Templates: ``<app_label>/<model_name>_confirm_delete.html``
    Context:
        object
            the original object being deleted
    """
    if extra_context is None: extra_context = {}
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    obj = lookup_object(model, object_id, slug, slug_field)

    if request.method == 'POST':
        obj.delete()
        msg = ugettext("The %(verbose_name)s was deleted.") %\
                                    {"verbose_name": model._meta.verbose_name}
        messages.success(request, msg, fail_silently=True)
        return HttpResponseRedirect(post_delete_redirect)
    else:
        if not template_name:
            template_name = "%s/%s_confirm_delete.html" % (
                model._meta.app_label, model._meta.object_name.lower())
        t = template_loader.get_template(template_name)
        c = RequestContext(request, {
            template_object_name: obj,
        }, context_processors)
        apply_extra_context(extra_context, c)
        response = HttpResponse(t.render(c))
        populate_xheaders(request, response, model,
                          getattr(obj, obj._meta.pk.attname))
        return response
def create_object(request,
                  model=None,
                  template_name=None,
                  template_loader=loader,
                  extra_context=None,
                  post_save_redirect=None,
                  login_required=False,
                  context_processors=None,
                  form_class=None):
    """
    Generic object-creation function.

    Templates: ``<app_label>/<model_name>_form.html``
    Context:
        form
            the form for the object
    """
    if extra_context is None: extra_context = {}
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    model, form_class = get_model_and_form_class(model, form_class)
    if request.method == 'POST':
        form = form_class(request.POST, request.FILES)
        if form.is_valid():
            new_object = form.save()

            msg = ugettext("The %(verbose_name)s was created successfully.") %\
                                    {"verbose_name": model._meta.verbose_name}
            messages.success(request, msg, fail_silently=True)
            return redirect(post_save_redirect, new_object)
    else:
        form = form_class()

    # Create the template, context, response
    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label,
                                             model._meta.object_name.lower())
    t = template_loader.get_template(template_name)
    c = RequestContext(request, {
        'form': form,
    }, context_processors)
    apply_extra_context(extra_context, c)
    return HttpResponse(t.render(c))
Beispiel #12
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
 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(u'%(?!\()', u'%%', 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(u'%(?!\()', u'%%', 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:
         with translation.override(None):
             result = self.render(context)
     return result
Beispiel #14
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': form.base_fields.keys()})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title': _('Change password: %s') % escape(user.username),
            'adminForm': adminForm,
            'form_url': mark_safe(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)
 def render(self, context):
     from my_django.conf import settings
     context[self.variable] = [(k, translation.ugettext(v))
                               for k, v in settings.LANGUAGES]
     return ''
 def get_form_error(self):
     return ugettext("Please correct the duplicate values below.")