Example #1
0
 def render(self, name=None, value=None, attrs=None, choices=()):
     name = name or self.name
     value = value or self.value
     attrs = attrs or self.attrs
     if 'id' in self.attrs:
         label_for = format_html(' for="{0}_{1}"', self.attrs['id'], self.index)
     else:
         label_for = ''
     choice_label = force_text(self.choice_label)
     return format_html('<label{0}>{1} {2}</label>', label_for, self.tag(), choice_label)
Example #2
0
def paginator_number(cl, i):
    """
    Generates an individual page index link in a paginated list.
    """
    if i == DOT:
        return "... "
    elif i == cl.page_num:
        return format_html('<span class="this-page">{0}</span> ', i + 1)
    else:
        return format_html(
            '<a href="{0}"{1}>{2}</a> ',
            cl.get_query_string({PAGE_VAR: i}),
            mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ""),
            i + 1,
        )
Example #3
0
 def model_index_html(self, request, model, site):
     fields = self.field_dict(model)
     if not fields:
         return ''
     return format_html('<p class="filter"><strong>View calendar by:</strong> {0}</p>',
                        format_html_join(', ', '<a href="calendars/{0}/">{1}</a>',
                                         ((f.name, force_text(capfirst(f.verbose_name))) for f in fields.values())))
Example #4
0
 def as_ul(self):
     if not self: return ''
     return format_html('<ul class="errorlist">{0}</ul>',
                        format_html_join('', '<li>{0}{1}</li>',
                                         ((k, force_text(v))
                                          for k, v in self.items())
                        ))
Example #5
0
 def as_ul(self):
     if not self: return ''
     return format_html('<ul class="errorlist">{0}</ul>',
                        format_html_join('', '<li>{0}</li>',
                                         ((force_text(e),) for e in self)
                                         )
                        )
Example #6
0
 def tag(self):
     if 'id' in self.attrs:
         self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index)
     final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value)
     if self.is_checked():
         final_attrs['checked'] = 'checked'
     return format_html('<input{0} />', flatatt(final_attrs))
Example #7
0
 def label_tag(self):
     attrs = {}
     if not self.is_first:
         attrs["class"] = "inline"
     label = self.field['label']
     return format_html('<label{0}>{1}:</label>',
                        flatatt(attrs),
                        capfirst(force_text(label)))
Example #8
0
 def render_css(self):
     # To keep rendering order consistent, we can't just iterate over items().
     # We need to sort the keys, and iterate over the sorted list.
     media = sorted(self._css.keys())
     return chain(*[
             [format_html('<link href="{0}" type="text/css" media="{1}" rel="stylesheet" />', self.absolute_path(path), medium)
                 for path in self._css[medium]]
             for medium in media])
Example #9
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     if value != '':
         # Only add the 'value' attribute if a value is non-empty.
         final_attrs['value'] = force_text(self._format_value(value))
     return format_html('<input{0} />', flatatt(final_attrs))
Example #10
0
 def render(self, name, value, attrs=None, choices=()):
     if value is None: value = []
     final_attrs = self.build_attrs(attrs, name=name)
     output = [format_html('<select multiple="multiple"{0}>', flatatt(final_attrs))]
     options = self.render_options(choices, value)
     if options:
         output.append(options)
     output.append('</select>')
     return mark_safe('\n'.join(output))
Example #11
0
 def test_format_html(self):
     self.assertEqual(
         html.format_html("{0} {1} {third} {fourth}",
                          "< Dangerous >",
                          html.mark_safe("<b>safe</b>"),
                          third="< dangerous again",
                          fourth=html.mark_safe("<i>safe again</i>")
                          ),
         "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>"
         )
Example #12
0
    def render(self, context):
        csrf_token = context.get("csrf_token", None)
        if csrf_token:
            if csrf_token == "NOTPROVIDED":
                return format_html("")
            else:
                return format_html(
                    "<div><input type='hidden' name='csrfmiddlewaretoken' value='{0}' /></div>", csrf_token
                )
        else:
            # It's very probable that the token is missing because of
            # misconfiguration, so we raise a warning
            from djangocg.conf import settings

            if settings.DEBUG:
                import warnings

                warnings.warn(
                    "A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext."
                )
            return ""
Example #13
0
 def render(self, name, value, attrs=None):
     final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
     try:
         result = self.check_test(value)
     except: # Silently catch exceptions
         result = False
     if result:
         final_attrs['checked'] = 'checked'
     if not (value is True or value is False or value is None or value == ''):
         # Only add the 'value' attribute if a value is non-empty.
         final_attrs['value'] = force_text(value)
     return format_html('<input{0} />', flatatt(final_attrs))
Example #14
0
 def render_option(self, selected_choices, option_value, option_label):
     option_value = force_text(option_value)
     if option_value in selected_choices:
         selected_html = mark_safe(' selected="selected"')
         if not self.allow_multiple_selected:
             # Only allow for a single selection.
             selected_choices.remove(option_value)
     else:
         selected_html = ''
     return format_html('<option value="{0}"{1}>{2}</option>',
                        option_value,
                        selected_html,
                        force_text(option_label))
Example #15
0
 def render_options(self, choices, selected_choices):
     # Normalize to strings.
     selected_choices = set(force_text(v) for v in selected_choices)
     output = []
     for option_value, option_label in chain(self.choices, choices):
         if isinstance(option_label, (list, tuple)):
             output.append(format_html('<optgroup label="{0}">', force_text(option_value)))
             for option in option_label:
                 output.append(self.render_option(selected_choices, *option))
             output.append('</optgroup>')
         else:
             output.append(self.render_option(selected_choices, option_value, option_label))
     return '\n'.join(output)
Example #16
0
 def render(self, name, value, attrs=None, choices=()):
     if value is None: value = []
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     id_ = final_attrs.get('id', None)
     inputs = []
     for i, v in enumerate(value):
         input_attrs = dict(value=force_text(v), **final_attrs)
         if id_:
             # An ID attribute was given. Add a numeric index as a suffix
             # so that the inputs don't all have the same ID attribute.
             input_attrs['id'] = '%s_%s' % (id_, i)
         inputs.append(format_html('<input{0} />', flatatt(input_attrs)))
     return mark_safe('\n'.join(inputs))
Example #17
0
    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = ['<ul>']
        # Normalize to strings
        str_values = set([force_text(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = format_html(' for="{0}"', final_attrs['id'])
            else:
                label_for = ''

            cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
            option_value = force_text(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = force_text(option_label)
            output.append(format_html('<li><label{0}>{1} {2}</label></li>',
                                      label_for, rendered_cb, option_label))
        output.append('</ul>')
        return mark_safe('\n'.join(output))
Example #18
0
    def label_tag(self, contents=None, attrs=None):
        """
        Wraps the given contents in a <label>, if the field has an ID attribute.
        contents should be 'mark_safe'd to avoid HTML escaping. If contents
        aren't given, uses the field's HTML-escaped label.

        If attrs are given, they're used as HTML attributes on the <label> tag.
        """
        contents = contents or conditional_escape(self.label)
        widget = self.field.widget
        id_ = widget.attrs.get('id') or self.auto_id
        if id_:
            attrs = attrs and flatatt(attrs) or ''
            contents = format_html('<label for="{0}"{1}>{2}</label>',
                                   widget.id_for_label(id_), attrs, contents
                                   )
        return mark_safe(contents)
Example #19
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 #20
0
    def format_callback(obj):
        has_admin = obj.__class__ in admin_site._registry
        opts = obj._meta

        if has_admin:
            admin_url = reverse('%s:%s_%s_change'
                                % (admin_site.name,
                                   opts.app_label,
                                   opts.object_name.lower()),
                                None, (quote(obj._get_pk_val()),))
            p = '%s.%s' % (opts.app_label,
                           opts.get_delete_permission())
            if not user.has_perm(p):
                perms_needed.add(opts.verbose_name)
            # Display a link to the admin page.
            return format_html('{0}: <a href="{1}">{2}</a>',
                               capfirst(opts.verbose_name),
                               admin_url,
                               obj)
        else:
            # Don't display link to edit, because it either has no
            # admin or is edited inline.
            return '%s: %s' % (capfirst(opts.verbose_name),
                                force_text(obj))
Example #21
0
    def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = '%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = format_html('<a href="{0}">{1}</a>',
                                                   value.url,
                                                   force_text(value))
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)
Example #22
0
 def xhtml(self):
     "Returns XHTML information needed for IE VML overlays."
     return format_html('<html xmlns="http://www.w3.org/1999/xhtml" {0}>', self.xmlns)
Example #23
0
 def style(self):
     "Returns additional CSS styling needed for Google Maps on IE."
     return format_html('<style type="text/css">{0}</style>', self.vml_css)
Example #24
0
 def scripts(self):
     "Returns all <script></script> tags required with Google Maps JavaScript."
     return format_html('%s\n  <script type="text/javascript">\n//<![CDATA[\n%s//]]>\n  </script>', self.api_script, mark_safe(self.js))
Example #25
0
 def api_script(self):
     "Returns the <script> tag for the Google Maps API javascript."
     return format_html('<script src="{0}{1}" type="text/javascript"></script>',
                        self.api_url, self.key)
Example #26
0
 def onload(self):
     "Returns the `onload` HTML <body> attribute."
     return format_html('onload="{0}.{1}_load()"', self.js_module, self.dom_id)
Example #27
0
 def body(self):
     "Returns HTML body tag for loading and unloading Google Maps javascript."
     return format_html('<body {0} {1}>', self.onload, self.onunload)
Example #28
0
def result_headers(cl):
    """
    Generates the list column headers.
    """
    ordering_field_columns = cl.get_ordering_field_columns()
    for i, field_name in enumerate(cl.list_display):
        text, attr = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True)
        if attr:
            # Potentially not sortable

            # if the field is the action checkbox: no sorting and special class
            if field_name == "action_checkbox":
                yield {"text": text, "class_attrib": mark_safe(' class="action-checkbox-column"'), "sortable": False}
                continue

            admin_order_field = getattr(attr, "admin_order_field", None)
            if not admin_order_field:
                # Not sortable
                yield {"text": text, "sortable": False}
                continue

        # OK, it is sortable if we got this far
        th_classes = ["sortable"]
        order_type = ""
        new_order_type = "asc"
        sort_priority = 0
        sorted = False
        # Is it currently being sorted on?
        if i in ordering_field_columns:
            sorted = True
            order_type = ordering_field_columns.get(i).lower()
            sort_priority = list(ordering_field_columns).index(i) + 1
            th_classes.append("sorted %sending" % order_type)
            new_order_type = {"asc": "desc", "desc": "asc"}[order_type]

        # build new ordering param
        o_list_primary = []  # URL for making this field the primary sort
        o_list_remove = []  # URL for removing this field from sort
        o_list_toggle = []  # URL for toggling order type for this field
        make_qs_param = lambda t, n: ("-" if t == "desc" else "") + str(n)

        for j, ot in ordering_field_columns.items():
            if j == i:  # Same column
                param = make_qs_param(new_order_type, j)
                # We want clicking on this header to bring the ordering to the
                # front
                o_list_primary.insert(0, param)
                o_list_toggle.append(param)
                # o_list_remove - omit
            else:
                param = make_qs_param(ot, j)
                o_list_primary.append(param)
                o_list_toggle.append(param)
                o_list_remove.append(param)

        if i not in ordering_field_columns:
            o_list_primary.insert(0, make_qs_param(new_order_type, i))

        yield {
            "text": text,
            "sortable": True,
            "sorted": sorted,
            "ascending": order_type == "asc",
            "sort_priority": sort_priority,
            "url_primary": cl.get_query_string({ORDER_VAR: ".".join(o_list_primary)}),
            "url_remove": cl.get_query_string({ORDER_VAR: ".".join(o_list_remove)}),
            "url_toggle": cl.get_query_string({ORDER_VAR: ".".join(o_list_toggle)}),
            "class_attrib": format_html(' class="{0}"', " ".join(th_classes)) if th_classes else "",
        }
Example #29
0
def items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """
    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_class = ""
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except (AttributeError, ObjectDoesNotExist):
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            if f is None:
                if field_name == "action_checkbox":
                    row_class = mark_safe(' class="action-checkbox"')
                allow_tags = getattr(attr, "allow_tags", False)
                boolean = getattr(attr, "boolean", False)
                if boolean:
                    allow_tags = True
                result_repr = display_for_value(value, boolean)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_class = mark_safe(' class="nowrap"')
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = EMPTY_CHANGELIST_VALUE
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f)
                if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
                    row_class = mark_safe(' class="nowrap"')
        if force_text(result_repr) == "":
            result_repr = mark_safe("&nbsp;")
        # If list_display_links not defined, add the link tag to the first field
        if (first and not cl.list_display_links) or field_name in cl.list_display_links:
            table_tag = {True: "th", False: "td"}[first]
            first = False
            url = cl.url_for_result(result)
            # Convert the pk to something that can be used in Javascript.
            # Problem cases are long ints (23L) and non-ASCII strings.
            if cl.to_field:
                attr = str(cl.to_field)
            else:
                attr = pk
            value = result.serializable_value(attr)
            result_id = repr(force_text(value))[1:]
            yield format_html(
                '<{0}{1}><a href="{2}"{3}>{4}</a></{5}>',
                table_tag,
                row_class,
                url,
                format_html(' onclick="opener.dismissRelatedLookupPopup(window, {0}); return false;"', result_id)
                if cl.is_popup
                else "",
                result_repr,
                table_tag,
            )
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if (
                form
                and field_name in form.fields
                and not (field_name == cl.model._meta.pk.name and form[cl.model._meta.pk.name].is_hidden)
            ):
                bf = form[field_name]
                result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
            yield format_html("<td{0}>{1}</td>", row_class, result_repr)
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield format_html("<td>{0}</td>", force_text(form[cl.model._meta.pk.name]))
Example #30
0
def _boolean_icon(field_val):
    icon_url = static("admin/img/icon-%s.gif" % {True: "yes", False: "no", None: "unknown"}[field_val])
    return format_html('<img src="{0}" alt="{1}" />', icon_url, field_val)