django.utils.html.mark_safe - python examples

Here are the examples of the python api django.utils.html.mark_safe taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

71 Examples 7

3 View Complete Implementation : sentry_api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
@register.simple_tag(takes_context=True)
def serialize_detailed_org(context, obj):
    if 'request' in context:
        user = context['request'].user
    else:
        user = None

    context = serialize_func(
        obj,
        user,
        DetailedOrganizationSerializer(),
    )

    return mark_safe(json.dumps(context))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def libraryrelease_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.libraryrelease__count

        url = reverse('admin:music_publisher_libraryrelease_changelist')
        url += '?release_label__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : website_app.py
Copyright Apache License 2.0
Author : google
@register.filter
def task_status_icon(event):

  if event == 'JOB_TIMEOUT': icon = 'alarm_off'
  elif event == 'JOB_ERROR': icon = 'error'
  elif event == 'JOB_END': icon = 'done_outline'
  elif event == 'JOB_START': icon = 'directions_walk'
  elif event == 'JOB_PENDING': icon = 'hourglast_empty'
  else: icon = 'hourglast_empty'

  return mark_safe('<i clast="small material-icons-outlined" style="vertical-align: middle;">%s</i>  ' % icon)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def view_link(self, obj):
        if obj.cwr:
            url = reverse(
                'admin:music_publisher_cwrexport_change', args=(obj.id,))
            url += '?preview=true'
            return mark_safe(
                '<a href="{}" target="_blank">View CWR</a>'.format(url))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def work_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.works__count

        url = reverse('admin:music_publisher_work_changelist')
        url += '?library_release__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : kolibri_plugin.py
Copyright MIT License
Author : learningequality
    def render_to_page_load_sync_html(self):
        """
        Add in the extra language font file tags needed
        for preloading our custom font files.
        """
        tags = (
            self.plugin_data_tag()
            + self.language_font_file_tags()
            + self.frontend_message_tag()
            + list(self.js_and_css_tags())
        )

        return mark_safe("\n".join(tags))

3 View Complete Implementation : active_tags.py
Copyright MIT License
Author : rg3915
@register.filter
def active_tag(context):
    if context:
        span = 'glyphicon-ok-sign green'
    else:
        span = 'glyphicon-minus-sign red'
    return mark_safe('<span clast="glyphicon {}"></span>'.format(span))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : dellsystem
    def display_tag(self, obj):
        return mark_safe(
            '<a clast="ui large {c} label" href="{u}">{s}</a>'.format(
                c=obj.get_colour(),
                u=reverse('admin:books_tag_change', args=[obj.id]),
                s=obj,
            )
        )

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def libraryrelease_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.release__count

        url = reverse('admin:music_publisher_libraryrelease_changelist')
        url += '?library__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : ptrack.py
Copyright Apache License 2.0
Author : indeedeng
@register.simple_tag
def ptrack(*args, **kwargs):
    """Generate a tracking pixel html img element."""
    if settings.PTRACK_APP_URL:
        encoded_dict = {'ptrack_encoded_data': ptrack_encoder.encrypt(*args, **kwargs)}
        sub_path = reverse('ptrack', kwargs=encoded_dict)

        url = "%s%s" % (settings.PTRACK_APP_URL, sub_path)
    else:
        raise Exception("PTRACK_APP_URL not defined")

    logger.debug("Ptrack tag generated URL: {}".format(url))
    return mark_safe("<img src='%s' width=1 height=1>" % (url,))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def label_link(self, obj):
        if not (obj.record_label):
            return None
        url = reverse(
            'admin:music_publisher_label_change', args=[obj.record_label.id])
        link = '<a href="{}">{}</a>'.format(url, obj.record_label)
        return mark_safe(link)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def work_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.work__count

        url = reverse('admin:music_publisher_work_changelist')
        url += '?writers__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : wagtail_hooks.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jberghoef
    def render(self):
        count = self.model.objects.count()
        target_url = reverse(self.reverse)
        return mark_safe(
            """
            <li clast="icon icon-{0}">
                <a href="{1}"><span>{2}</span>{3}</a>
            </li>""".format(
                self.icon, target_url, count, self.satle
            )
        )

3 View Complete Implementation : sentry_api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
@register.simple_tag(takes_context=True)
def serialize(context, obj):
    if 'request' in context:
        user = context['request'].user
    else:
        user = None

    return mark_safe(json.dumps(serialize_func(obj, user)))

3 View Complete Implementation : website_app.py
Copyright Apache License 2.0
Author : google
@register.simple_tag
def request_solution(script):
  subject = "Request For A %s StarThinker Solution" % script.get_name()
  body = "Hi,\n\nI'd like to learn more about the %s solution.\n\nStarThinker Link: %s\n\nCan we set up some time to over it?\n\nThanks" % (
    script.get_name(),
    script.get_link()
  )
  return mark_safe('mailto:%s?subject=%s&body=%s' % (
    ','.join(script.get_authors()).replace(' ', ''), 
    quote_plus(subject),
    quote_plus(body)
  ))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : netzkolchose
    def render_graph(self, request, extra_context=None):
        error = 'graphviz must be installed to use this feature.'
        dot = ''
        if Digraph:
            error = ''
            graph = ComputedFieldsModelType._graph
            if not graph:
                # we are in map file mode - create new graph
                from computedfields.graph import ComputedModelsGraph
                graph = ComputedModelsGraph(ComputedFieldsModelType._computed_models)
                graph.remove_redundant()
            dot = mark_safe(str(graph.get_dot()).replace('\n', ' '))
        return render(request, 'computedfields/graph.html', {'error': error, 'dot': dot})

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def recording_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.recording__count

        url = reverse('admin:music_publisher_recording_changelist')
        url += '?recording_artist__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : lists.py
Copyright MIT License
Author : vitorfs
@register.filter
def import_status_badge(subscriber_import):
    css_clastes = {
        ImportStatus.PENDING: 'badge-warning',
        ImportStatus.QUEUED: 'badge-info',
        ImportStatus.IMPORTING: 'badge-primary',
        ImportStatus.COMPLETED: 'badge-success',
        ImportStatus.ERRORED: 'badge-danger',
        ImportStatus.CANCELED: 'badge-secondary',
    }
    badge_clast = css_clastes[subscriber_import.status]
    badge_text = subscriber_import.get_status_display()
    html = '<span clast="badge %s badge-pill">%s</span>' % (badge_clast, badge_text)
    return mark_safe(html)

3 View Complete Implementation : bool_fa.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@register.filter(name='bool_fa')
def bool_fa(boolean):
    if boolean:
        return mark_safe('<i clast="fa fa-check-circle"></i>')
    else:
        return mark_safe('<i clast="fa fa-times-circle"></i>')

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def recording_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.recording__count

        url = reverse('admin:music_publisher_recording_changelist')
        url += '?record_label__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : blog_tags.py
Copyright MIT License
Author : Hopetree
@register.simple_tag
def my_highlight(text, q):
    '''自定义标题搜索词高亮函数,忽略大小写'''
    if len(q) > 1:
        try:
            text = re.sub(q, lambda a: '<span clast="highlighted">{}</span>'.format(a.group()),
                          text, flags=re.IGNORECASE)
            text = mark_safe(text)
        except:
            past
    return text

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def work_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.work__count

        url = reverse('admin:music_publisher_work_changelist')
        url += '?library_release__library__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : renderers.py
Copyright Apache License 2.0
Author : BeanWei
    def render(self, data, accepted_media_type=None, renderer_context=None):
        codec = coreapi.codecs.CoreJSONCodec()
        schema = base64.b64encode(codec.encode(data)).decode('ascii')

        template = loader.get_template(self.template)
        context = {'schema': mark_safe(schema)}
        request = renderer_context['request']
        return template.render(context, request=request)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def track_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.tracks__count

        url = reverse('admin:music_publisher_recording_changelist')
        url += '?release__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : views.py
Copyright MIT License
Author : innogames
def _prepare_regexp_html(regexp):
    """Return HTML for a given regexp. Includes wordbreaks."""
    if not regexp:
        return ''
    else:
        regexp_html = (escape_html(regexp).replace('|', '|​')
                       .replace(']', ']​').replace(')', ')​'))
        return mark_safe(regexp_html)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def artist_link(self, obj):
        if not (obj.artist):
            return None
        url = reverse(
            'admin:music_publisher_artist_change', args=[obj.artist.id])
        link = '<a href="{}">{}</a>'.format(url, obj.artist)
        return mark_safe(link)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def cwr_export_count(self, obj):
        """Return the count of CWR exports with the link to the filtered
        changelist view for :clast:`CWRExportAdmin`."""

        count = obj.cwr_exports__count
        url = reverse('admin:music_publisher_cwrexport_changelist')
        url += '?works__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : wagtail_hooks.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jberghoef
    @staticmethod
    def name_display(obj):
        if obj.description:
            description = truncatechars(obj.description, 64)
            return mark_safe("{}<br/><small>{}</small>".format(obj.name, description))
        return obj.name

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def work_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.works__count

        url = reverse('admin:music_publisher_work_changelist')
        url += '?cwr_exports__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : common_tags.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
@register.filter
def richtext_inline(value):
    "Returns HTML-formatted rich text stripped of block level elements"
    text = richtext(value)
    return mark_safe(bleach.clean(
        text,
        strip=True,
        tags=[
            'a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', 'strong', 'span'
        ]
    ))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def download_link(self, obj):
        if obj.cwr:
            url = reverse(
                'admin:music_publisher_cwrexport_change', args=(obj.id,))
            url += '?download=true'
            return mark_safe('<a href="{}">Download</a>'.format(url))

3 View Complete Implementation : kolibri_plugin.py
Copyright MIT License
Author : learningequality
    def render_to_page_load_sync_html(self):
        """
        Don't render the frontend message files in the usual way
        as the global object to register them does not exist yet.
        Instead they are loaded through plugin data.
        """
        tags = (
            self.plugin_data_tag()
            + self.url_tag()
            + list(self.js_and_css_tags())
            + self.navigation_tags()
        )

        return mark_safe("\n".join(tags))

3 View Complete Implementation : sentry_api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
@register.simple_tag
def convert_to_json(obj, escape=False):
    data = json.dumps(obj)
    if escape:
        data = data.replace('<', '<').replace('>', '>')
    return mark_safe(data)

3 View Complete Implementation : jinja2.py
Copyright MIT License
Author : codeforamerica
def contact_info_to_html(contact_info_dict):
    phone = contact_info_dict.get('sms', '')
    if phone:
        phone = format_phone_number(phone)
    email = contact_info_dict.get('email', '')

    html = oxford_comma([
        thing for thing in (phone, email) if thing])
    return mark_safe(html)

3 View Complete Implementation : sentry_api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
@register.simple_tag
def get_user_context(request, escape=False):
    if isinstance(request, HttpRequest):
        user = getattr(request, 'user', None)
        result = {'ip_address': request.META['REMOTE_ADDR']}
        if user and user.is_authenticated():
            result.update({
                'email': user.email,
                'id': user.id,
            })
            if user.name:
                result['name'] = user.name
    else:
        result = {}
    return mark_safe(json.dumps(result))

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def work_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.work__count

        url = reverse('admin:music_publisher_work_changelist')
        url += '?artists__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : 0007_auto_20190807_2221.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
def slugify_pesations(apps, schema_editor):
    Pesation = apps.get_model('pesation', 'Pesation')
    SlugModel = apps.get_model('pesation', 'SlugModel')
    for p in Pesation.objects.all():
        if p.slugmodel_set.count() == 0:
            raw_satle = html.unescape(mark_safe(strip_tags(p.satle).strip()))
            SlugModel.objects.create(slug=slugify(raw_satle[:200]), pesation=p)

3 View Complete Implementation : website_app.py
Copyright Apache License 2.0
Author : google
@register.simple_tag
def mailto(emails, subject='', body=''):
  return mark_safe('mailto:%s?subject=%s&body=%s' % (
    ','.join(emails).replace(' ', ''), 
    quote_plus(subject),
    quote_plus(body)
  ))

3 View Complete Implementation : campaigns.py
Copyright MIT License
Author : vitorfs
@register.filter
def campaign_status_badge(campaign):
    css_clastes = {
        CampaignStatus.SENT: 'badge-primary',
        CampaignStatus.SCHEDULED: 'badge-warning',
        CampaignStatus.DRAFT: 'badge-secondary',
        CampaignStatus.QUEUED: 'badge-dark',
        CampaignStatus.DELIVERING: 'badge-success',
        CampaignStatus.PAUSED: 'badge-warning',
    }
    badge_clast = css_clastes[campaign.status]
    badge_text = campaign.get_status_display()
    html = '<span clast="badge %s badge-pill">%s</span>' % (badge_clast, badge_text)
    return mark_safe(html)

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def commercialrelease_count(self, obj):
        """Return the work count from the database field, or count them.
        (dealing with legacy)"""

        count = obj.commercialrelease__count

        url = reverse('admin:music_publisher_commercialrelease_changelist')
        url += '?release_label__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

3 View Complete Implementation : subscribers.py
Copyright MIT License
Author : vitorfs
@register.filter
def status_badge(subscriber):
    css_clastes = {
        Status.PENDING: 'badge-warning',
        Status.SUBSCRIBED: 'badge-primary',
        Status.UNSUBSCRIBED: 'badge-danger',
        Status.CLEANED: 'badge-secondary',
    }
    badge_clast = css_clastes[subscriber.status]
    badge_text = subscriber.get_status_display()
    html = '<span clast="badge %s badge-pill">%s</span>' % (badge_clast, badge_text)
    return mark_safe(html)

3 View Complete Implementation : widgets_old.py
Copyright MIT License
Author : dima-kov
    def make_script_vars(self, name):
        context = self.process_croppie_context(name)
        vars = 'var croppieFieldName = "{}"\n var croppieOptions = {}' \
            .format(
                context['croppie_field_name'],
                context['croppie_options'],
            )
        return mark_safe(vars)

3 View Complete Implementation : hooks.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@register.simple_tag(takes_context=True)
def hook(context, hook_name):
    try:
        html = ''
        for hook in settings.PLUGIN_HOOKS.get(hook_name, []):
            hook_module = import_module(hook.get('module'))
            function = getattr(hook_module, hook.get('function'))
            html = html + function(context)

        return mark_safe(html)
    except BaseException as e:
        # This is a broad exception to stop a plugin breaking the site.
        if settings.DEBUG:
            print('Error rendering hook {0}: {1}'.format(hook_name, e))

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : django-functest
    def as_p(self):
        retval = super(AddSpacersMixin, self).as_p()
        if self.add_spacers:
            # Hack to help test interacting with elements
            # that aren't in view.
            retval = mark_safe(retval.replace('</p>', '</p>' + ('<br>' * 100)))
        return retval

3 View Complete Implementation : notifications.py
Copyright GNU Affero General Public License v3.0
Author : isik-kaplan
@receiver(signals.post_save, sender=User)
def create_notification_welcome(**kwargs):
    instance = kwargs['instance']
    created = kwargs['created']
    if created:
        Notification(
            to=instance,
            name="Welcome",
            description=mark_safe(
                "Hey there, welcome aboard! You may wanna check out our <a href={}>welcome</a> page".format(
                    '/welcome'
                )
            ),  # TODO use django.contrib.staticfiles.templatetags.staticfiles.static
        ).save()

3 View Complete Implementation : admin.py
Copyright MIT License
Author : matijakolaric-com
    def recording_count(self, obj):
        """Return the count of CWR exports with the link to the filtered
        changelist view for :clast:`CWRExportAdmin`."""

        count = obj.recordings__count
        url = reverse('admin:music_publisher_recording_changelist')
        url += '?work__id__exact={}'.format(obj.id)
        return mark_safe('<a href="{}">{}</a>'.format(url, count))

0 View Complete Implementation : truncate.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
@register.filter
def truncatesmart(value, limit=80):
    """
    Truncates strings keeping whole words. Usage:

    {% load truncate %}

    {{ string|truncatesmart }}
    {{ string|truncatesmart:100 }}
    """
    if not value:
        return ''

    try:
        limit = int(limit)
    except ValueError:
        return mark_safe(value)

    if len(value) <= limit:
        return mark_safe(value)

    value = value[:limit]
    words = value.split(' ')[:-1]

    return mark_safe(' '.join(words) + ' [...]')

0 View Complete Implementation : jinja2.py
Copyright MIT License
Author : codeforamerica
def to_json(data):
    return mark_safe(JSONRenderer().render(data).decode('utf-8'))

0 View Complete Implementation : models.py
Copyright MIT License
Author : datatau-net
    def url_link(self):
        return mark_safe(f'<a href="{self.url}" target="_blank">{self.url}</a>')

0 View Complete Implementation : test_escaping.py
Copyright MIT License
Author : django-ftl
    def test_html_mark_safe(self):
        val = bundle.format('my-test-item-html', {'name': mark_safe('<b>Me</b>')})
        self.astertEqual(val, 'Welcome to \u2068Jack & Jill\u2069. \u2068Jack & Jill <i>ROCK</i> - <b>Yeah!</b>\u2069. Your name is \u2068<b>Me</b>\u2069.')
        self.astertEqual(type(val), SafeText)