Python django.utils.html.format_html() Examples

The following are 30 code examples of django.utils.html.format_html(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.html , or try the search function .
Example #1
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 7 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example #2
Source File: admin.py    From django-healthchecks with MIT License 7 votes vote down vote up
def last_beat_column(self, object):
        last_beat = object.last_beat
        if is_aware(last_beat):
            # Only for USE_TZ=True
            last_beat = localtime(last_beat)

        last_beat_str = localize(last_beat)
        if object.is_expired:
            # Make clearly visible
            alert_icon = static('admin/img/icon-alert.svg')
            return format_html(
                '<div style="vertical-align: middle; display: inline-block;">'
                '  <img src="{}" style="vertical-align: middle;"> '
                '  <span style="color: #efb80b; vertical-align: middle;">{}</span>'
                '</div>',
                alert_icon, last_beat_str
            )
        else:
            return last_beat_str 
Example #3
Source File: relfield.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def build_attrs(self, attrs={}, extra_attrs=None, **kwargs):
        to_opts = self.rel.to._meta
        if "class" not in attrs:
            attrs['class'] = 'select-search'
        else:
            attrs['class'] = attrs['class'] + ' select-search'
        attrs['data-search-url'] = self.admin_view.get_admin_url(
            '%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
        attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
        attrs['data-choices'] = '?'
        if self.rel.limit_choices_to:
            for i in list(self.rel.limit_choices_to):
                attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
            attrs['data-choices'] = format_html(attrs['data-choices'])
        if DJANGO_11:
            attrs.update(kwargs)
            return super(ForeignKeySearchWidget, self).build_attrs(attrs, extra_attrs=extra_attrs)
        else:
            if extra_attrs:
                attrs.update(extra_attrs)
            return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs) 
Example #4
Source File: base.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render(self, name, value, attrs=None):

        date_format = "yyyy-MM-dd"

        if "format" not in self.attrs:
            attrs['format'] = date_format

        if "data-format" not in self.attrs:
            attrs['data-format'] = date_format

        field = super(DatepickerInput, self).render(name, value, attrs)
        final_attrs = self.build_attrs(attrs)

        output = format_html(u'''
         <div class="input-append date datepicker" data-provide="datepicker" {0}>
            {1}
            <span class="add-on">
                <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
            </span>
        </div>
        ''', flatatt(final_attrs), field)

        return mark_safe(output) 
Example #5
Source File: base.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render(self, name, value, attrs=None):

        date_format = "yyyy-MM-dd hh:mm"

        if "data-format" not in self.attrs:
            attrs['data-format'] = date_format
        if "class" not in self.attrs:
            attrs['class'] = 'input-medium'

        field = super(DateTimePickerInput, self).render(name, value, attrs)
        final_attrs = self.build_attrs(attrs)

        output = format_html(u'''
         <div class="input-append date datetimepicker" {0}>
            {1}
            <span class="add-on">
                <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
            </span>
        </div>
        ''', flatatt(final_attrs), field)

        return mark_safe(output) 
Example #6
Source File: widgets.py    From django-fontawesome with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render_option(self, selected_choices, option_value, option_label):
            if option_value is None:
                option_value = ''
            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 data-icon="{0}" value="{0}"{1}>{2}</option>',
                option_value,
                selected_html,
                force_text(option_label),
            ) 
Example #7
Source File: tables.py    From aswan with GNU Lesser General Public License v2.1 5 votes vote down vote up
def render_action(cls, record):
        url = reverse('permissions:group_update')
        html = (
            '''
            <a href="{1}?entity_id={0}"
               style="margin-right: 10px">变更权限
            </a>
            <a data-entity_id={0}
               class="perms-group-delete">删除
            </a>
            '''
        ).format(record.get('entity_id', ''), url)
        return format_html(html) 
Example #8
Source File: models.py    From yata with GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        return format_html("{} event {}".format(self.faction, self.title)) 
Example #9
Source File: tables.py    From aswan with GNU Lesser General Public License v2.1 5 votes vote down vote up
def render_desc(cls, value, record):
        url = reverse('permissions:group_update')
        html = '<a href="{}?entity_id={}">{}</a>'.format(
            url, record.get('entity_id', ''), value,
        )
        return format_html(html) 
Example #10
Source File: tables.py    From aswan with GNU Lesser General Public License v2.1 5 votes vote down vote up
def render_action(cls, record):
        url = reverse('permissions:uri_group_update')
        html = (
            '''
            <a href="{1}?entity_id={0}"
               style="margin-right: 10px">变更权限
            </a>
            <a data-entity_id={0}
               class="perms-uri-group-delete">删除
            </a>
            '''
        ).format(record.get('entity_id', ''), url)
        return format_html(html) 
Example #11
Source File: tables.py    From aswan with GNU Lesser General Public License v2.1 5 votes vote down vote up
def render_desc(cls, value, record):
        url = reverse('permissions:uri_group_update')
        html = '<a href="{}?entity_id={}">{}</a>'.format(
            url, record.get('entity_id', ''), value,
        )
        return format_html(html) 
Example #12
Source File: widgets.py    From django-osm-field with MIT License 5 votes vote down vote up
def render_osmfield(self, id_):
        # we need {{ and }} because of .format() working with {}
        return format_html(
            '<script type="application/javascript">$(function()'
            '{{$("#{0}").osmfield();}});</script>',
            id_,
        ) 
Example #13
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def render(self):
        id_ = self.attrs.get('id', None)
        start_tag = format_html('<div id="{0}">', id_) if id_ else '<div>'
        output = [start_tag]
        for widget in self:
            output.append(format_html(u'<span>{0}</span>', force_text(widget)))
        output.append('</span>')
        return mark_safe('\n'.join(output)) 
Example #14
Source File: models.py    From yata with GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        return format_html("{} {} [{}]".format(self.faction, self.crime_name, self.tId)) 
Example #15
Source File: app_filters.py    From yata with GNU General Public License v3.0 5 votes vote down vote up
def trURL(string):
    regex = r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)"
    words = []
    for w in string.split():
        if re.match(regex, w):
            words.append(format_html('<a href="{}" target="_blank">{}</a>', escape(w), escape(w)))
        else:
            words.append(escape(w))
    return format_html(" ".join(words)) 
Example #16
Source File: app_filters.py    From yata with GNU General Public License v3.0 5 votes vote down vote up
def signColor(i, inv=False):
    if i > 0:
        cl = "error" if inv else "valid"
        return format_html('<span class="{}">{:+,.0f}</span>'.format(escape(cl), i))
    elif i < 0:
        cl = "valid" if inv else "error"
        return format_html('<span class="{}">{:+,.0f}</span>'.format(escape(cl), i))
    else:
        return '' 
Example #17
Source File: admin.py    From django-useraudit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def activate(self, obj):
        UserModel = get_user_model()
        try:
            user = UserModel._default_manager.get_by_natural_key(obj.username)
            if user.is_active:
                return "Active"
            activation_url = reverse("useraudit:reactivate_user", args=[user.id])
            return format_html(u"<a href='%s'>Activate</a>" % activation_url)
        except UserModel.DoesNotExist:
            return "N/A" 
Example #18
Source File: tables.py    From aswan with GNU Lesser General Public License v2.1 5 votes vote down vote up
def render_fullname(cls, record):
        url = reverse('permissions:user_update')
        html = '<a href="{}?entity_id={}">{}</a>'.format(url, record.get(
            'entity_id', ''), record.get('fullname', record['pk']))
        return format_html(html) 
Example #19
Source File: admin.py    From django-qsessions with MIT License 5 votes vote down vote up
def session_data_decoded(self, obj):
        return format_html(
            '<pre style="white-space: pre-wrap; max-width: 800px; display: inline-block; direction: ltr;">{}</pre>',
            pformat(obj.get_decoded()),
        ) 
Example #20
Source File: wagtail_hooks.py    From readux with MIT License 5 votes vote down vote up
def global_admin_css():
    """Add /static/css/wagtail.css."""
    return format_html('<link rel="stylesheet" href="{}">', static("css/wagtail.css")) 
Example #21
Source File: gmap.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def style(self):
        "Returns additional CSS styling needed for Google Maps on IE."
        return format_html('<style type="text/css">{}</style>', self.vml_css) 
Example #22
Source File: gmap.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def scripts(self):
        "Returns all <script></script> tags required with Google Maps JavaScript."
        return format_html('{}\n  <script type="text/javascript">\n//<![CDATA[\n{}//]]>\n  </script>',
                           self.api_script, mark_safe(self.js)) 
Example #23
Source File: gmap.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def api_script(self):
        "Returns the <script> tag for the Google Maps API javascript."
        return format_html('<script src="{}{}" type="text/javascript"></script>',
                           self.api_url, self.key) 
Example #24
Source File: gmap.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def onload(self):
        "Returns the `onload` HTML <body> attribute."
        return format_html('onload="{}.{}_load()"', self.js_module, self.dom_id) 
Example #25
Source File: gmap.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def body(self):
        "Returns HTML body tag for loading and unloading Google Maps javascript."
        return format_html('<body {} {}>', self.onload, self.onunload) 
Example #26
Source File: admin_list.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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="{}" alt="{}" />', icon_url, field_val) 
Example #27
Source File: admin_list.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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">{}</span> ', i + 1)
    else:
        return format_html('<a href="{}"{}>{}</a> ',
                           cl.get_query_string({PAGE_VAR: i}),
                           mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
                           i + 1) 
Example #28
Source File: helpers.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def label_tag(self):
        attrs = {}
        if not self.is_first:
            attrs["class"] = "inline"
        label = self.field['label']
        return format_html('<label{}>{}:</label>',
                           flatatt(attrs),
                           capfirst(force_text(label))) 
Example #29
Source File: utils.py    From bioforum with MIT License 5 votes vote down vote up
def as_ul(self):
        if not self:
            return ''
        return format_html(
            '<ul class="errorlist">{}</ul>',
            format_html_join('', '<li>{}{}</li>', self.items())
        ) 
Example #30
Source File: models.py    From yata with GNU General Public License v3.0 5 votes vote down vote up
def fullname(self):
        return format_html("{} [{}]".format(self.name, self.tId))