Python django.utils.html.mark_safe() Examples

The following are 30 code examples of django.utils.html.mark_safe(). 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: views.py    From sfm-ui with MIT License 6 votes vote down vote up
def render_column(self, row, column):
        # We want to render user as a custom column
        if column == 'link':
            platform_type = self.collection.harvest_type.split('_')[0]
            return mark_safe(u'<a target="_blank" href="{0}"> <img src="{1}" alt="Link to {2} account for {3}" height="35" width="35"/></a>'.format(
                row.social_url(), static('ui/img/{}_logo.png'.format(platform_type)), platform_type, row.token))
        elif column == 'messages':
            msg_seed = ""
            for msg in self.seed_infos.get(row.seed_id, []):
                msg_seed += u'<li><p>{}</p></li>'.format(msg)
            for msg in self.seed_warnings.get(row.seed_id, []):
                msg_seed += u'<li><p>{}</p></li>'.format(msg)
            for msg in self.seed_errors.get(row.seed_id, []):
                msg_seed += u'<li><p>{}</p></li>'.format(msg)
            return mark_safe(u'<ul>{}</ul>'.format(msg_seed)) if msg_seed else ""

        elif column == 'uid':
            return mark_safe(u'<a href="{}">{}</a>'.format(reverse('seed_detail', args=[row.pk]),
                                                           row.uid)) if row.uid else ""
        elif column == 'token':
            return mark_safe(u'<a href="{}">{}</a>'.format(reverse('seed_detail', args=[row.pk]),
                                                           ui_extras.json_list(row.token))) if row.token else "" 
Example #2
Source File: test_compat.py    From django-compat with MIT License 6 votes vote down vote up
def test_format_html(self):
        """
        Test: format_html
        url: https://github.com/django/django/blob/stable/1.8.x/tests/utils_tests/test_html.py#L44-L53

        """

        from django.utils import html

        from compat import format_html

        self.assertEqual(
            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 #3
Source File: truncate.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
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) + ' [...]') 
Example #4
Source File: models.py    From wagtailvideos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def video_tag(self, attrs=None):
        if attrs is None:
            attrs = {}
        else:
            attrs = attrs.copy()
        if self.thumbnail:
            attrs['poster'] = self.thumbnail.url

        transcodes = self.transcodes.exclude(processing=True).filter(error_message__exact='')
        sources = []
        for transcode in transcodes:
            sources.append("<source src='{0}' type='video/{1}' >".format(transcode.url, transcode.media_format.name))

        mime = mimetypes.MimeTypes()
        sources.append("<source src='{0}' type='{1}'>"
                       .format(self.url, mime.guess_type(self.url)[0]))

        sources.append("<p>Sorry, your browser doesn't support playback for this video</p>")
        return mark_safe(
            "<video {0}>\n{1}\n</video>".format(flatatt(attrs), "\n".join(sources))) 
Example #5
Source File: calendars.py    From django-happenings with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def formatmonth(self, theyear, themonth, withyear=True, net=None, qs=None, template='happenings/partials/calendar/month_table.html'):
        """Return a formatted month as a table."""
        context = self.get_context()
        context['month_start_date'] = date(self.yr, self.mo, 1)
        context['week_rows'] = []
        for week in self.monthdays2calendar(theyear, themonth):
            week_row = []
            for day, weekday in week:
                week_row.append(self.formatday(day, weekday))
            context['week_rows'].append(week_row)

        nxt, prev = get_next_and_prev(net)
        extra_qs = ('&' + '&'.join(qs)) if qs else ''
        context['prev_qs'] = mark_safe('?cal_prev=%d%s' % (prev, extra_qs))
        context['next_qs'] = mark_safe('?cal_next=%d%s' % (nxt, extra_qs))
        context['withyear'] = withyear
        return render_to_string(template, context) 
Example #6
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def photo_list(request, course_slug, style='horiz'):
    if style not in PHOTO_LIST_STYLES:
        raise Http404
    user = get_object_or_404(Person, userid=request.user.username)
    if not has_photo_agreement(user):
        url = reverse('config:photo_agreement') + '?return=' + urllib.parse.quote(request.path)
        return ForbiddenResponse(request, mark_safe('You must <a href="%s">confirm the photo usage agreement</a> before seeing student photos.' % (url)))
    
    course = get_object_or_404(CourseOffering, slug=course_slug)
    members = Member.objects.filter(offering=course, role="STUD").select_related('person', 'offering')
    
    # fire off a task to fetch the photos and warm the cache
    pre_fetch_photos(m.person.emplid for m in members)

    context = {'course': course, 'members': members}
    return render(request, 'grades/photo_list_%s.html' % (style), context) 
Example #7
Source File: admin2.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def get_photo_preview(self, obj):
        photo_preview = render_to_string(
            "admin/products/includes/photo-preview.html",
            {"photo": obj, "product": obj.product},
        )
        return mark_safe(photo_preview) 
Example #8
Source File: admin4.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def first_photo(self, obj):
        project_photos = obj.productphoto_set.all()[:1]
        if project_photos.count() > 0:
            photo_preview = render_to_string(
                "admin/products/includes/photo-preview.html",
                {"photo": project_photos[0], "product": obj},
            )
            return mark_safe(photo_preview)
        return "" 
Example #9
Source File: admin3.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def first_photo(self, obj):
        project_photos = obj.productphoto_set.all()[:1]
        if project_photos.count() > 0:
            photo_preview = render_to_string(
                "admin/products/includes/photo-preview.html",
                {"photo": project_photos[0], "product": obj},
            )
            return mark_safe(photo_preview)
        return "" 
Example #10
Source File: ptrack.py    From django-ptrack with Apache License 2.0 5 votes vote down vote up
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 ImproperlyConfigured("PTRACK_APP_URL not defined")

    logger.debug("Ptrack tag generated URL: {}".format(url))
    return mark_safe("<img src='%s' width=1 height=1>" % (url,)) 
Example #11
Source File: cartoview_tags.py    From cartoview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dump_json(obj):
    # if obj is None:
    #     return "null"
    return mark_safe(json.dumps(obj)) 
Example #12
Source File: models.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 5 votes vote down vote up
def image_tag(self):
        return mark_safe(f'<img src="{self.image_url}" width="150" height="150" />') 
Example #13
Source File: controlcenter_tags.py    From django-controlcenter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def jsonify(obj):
    return mark_safe(json.dumps(obj, cls=DjangoJSONEncoder)) 
Example #14
Source File: admin2.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def get_first_photo(self, obj):
        project_photos = obj.productphoto_set.all()[:1]
        if project_photos.count() > 0:
            photo_preview = render_to_string(
                "admin/products/includes/photo-preview.html",
                {"photo": project_photos[0], "product": obj},
            )
            return mark_safe(photo_preview)
        return "" 
Example #15
Source File: blog_tags.py    From izone with MIT License 5 votes vote down vote up
def get_star(num):
    '''得到一排星星'''
    tag_i = '<i class="fa fa-star"></i>'
    return mark_safe(tag_i * num) 
Example #16
Source File: views.py    From izone with MIT License 5 votes vote down vote up
def regexview(request):
    if request.is_ajax() and request.method == "POST":
        data = request.POST
        texts = data.get('texts')
        regex = data.get('r')
        key = data.get('key')
        try:
            lis = re.findall(r'{}'.format(regex), texts)
        except:
            lis = []
        num = len(lis)
        if key == 'url' and num:
            script_tag = '''<script>$(".re-result p").children("a").attr({target:"_blank",rel:"noopener noreferrer"});</script>'''
            result = '<br>'.join(['[{}]({})'.format(i,i) for i in lis])
        else:
            script_tag = ''
            info = '\n'.join(lis)
            result = "匹配到&nbsp;{}&nbsp;个结果:\n".format(num) + "```\n" + info + "\n```"
        result = markdown.markdown(result, extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
        ])
        return JsonResponse({'result': mark_safe(result+script_tag), 'num': num})
    return render(request, 'tool/regex.html')

# 生成请求头 
Example #17
Source File: wagtailnews_admin_tags.py    From wagtailnews with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def newsitem_status(newsitem, link=True):
    buttons = []
    output = []
    if newsitem.live:
        buttons.append({
            'href': newsitem.url,
            'primary': True,
            'text': _('live'),
        })
    if newsitem.has_unpublished_changes or not newsitem.live:
        buttons.append({
            'href': reverse('wagtailnews:view_draft', kwargs={
                'pk': newsitem.newsindex.pk, 'newsitem_pk': newsitem.pk,
            }),
            'primary': False,
            'text': _('draft'),
        })

    if link:
        for button in buttons:
            output.append(format_html(
                '<a href="{}" target="_blank" class="{}">{}</a>',
                button['href'],
                'status-tag primary' if button['primary'] else 'status-tag',
                button['text']))
    else:
        for button in buttons:
            output.append(format_html(
                '<span class="{}">{}</span>',
                'status-tag primary' if button['primary'] else 'status-tag',
                button['text']))

    return mark_safe(' + '.join(output)) 
Example #18
Source File: models.py    From django-beginners-guide with MIT License 5 votes vote down vote up
def get_message_as_markdown(self):
        return mark_safe(markdown(self.message, safe_mode='escape')) 
Example #19
Source File: core_status_tags.py    From orcamentos with MIT License 5 votes vote down vote up
def status_icon(status):
    icons = {
        'n': '',
        'c': 'fa-close status-cancelado',
        'elab': 'fa-circle status-elab',
        'p': 'fa-circle status-pendente',
        'co': 'fa-check status-concluido',
        'a': 'fa-star status-aprovado'
    }
    return mark_safe('{}'.format(icons[status])) 
Example #20
Source File: models.py    From chi-councilmatic with MIT License 5 votes vote down vote up
def linked_description(self):
        # Sections
        description = re.sub(r'((Section)*s* *(\d{1,2}-\d{1,3}-\d+)\S*)',
                             r"<a href='https://chicagocode.org/\3/'>\1</a>",
                             self.title)

        # Chapters
        # 8 and 16-13
        description = re.sub(r'(\d{1,2}-\d{1,3} and )((\d{1,2})-\d{1,3})',
                             r"\1<a href='https://chicagocode.org/\3/\2/'>\2</a>",
                             description)
        # , 14-3, 12-1, 5-17 and
        description = re.sub(r'(?<=\d, )((\d{1,2})-\d{1,3})(?=, \d| and )',
                             r"<a href='https://chicagocode.org/\2/\1/'>\1</a>",
                             description)
        description = re.sub(r'(Chapters* ((\d{1,2})-\d{1,3}))',
                             r"<a href='https://chicagocode.org/\3/\2/'>\1</a>",
                             description)

        # Titles
        # 8 and 9
        description = re.sub(r'(\d{1,2} and )(\d{1,2})',
                             r"\1<a href='https://chicagocode.org/\2/'>\2</a>",
                             description)
        # , 3, 4, 4 and
        description = re.sub(r'(?<=\d, )(\d{1,2})(?=, \d| and )',
                             r"<a href='https://chicagocode.org/\1/'>\1</a>",
                             description)
        description = re.sub(r'(Titles* (\d{1,2}))',
                             r"<a href='https://chicagocode.org/\2/'>\1</a>",
                             description)

        return mark_safe(description) 
Example #21
Source File: renderers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
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) 
Example #22
Source File: active_tags.py    From django-experience with MIT License 5 votes vote down vote up
def active_tag(context):
    if context:
        span = 'glyphicon-ok-sign green'
    else:
        span = 'glyphicon-minus-sign red'
    return mark_safe('<span class="glyphicon {}"></span>'.format(span)) 
Example #23
Source File: json_utils.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def dumps_htmlsafe(value):
    return mark_safe(_default_escaped_encoder.encode(value)) 
Example #24
Source File: views.py    From django-functest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #25
Source File: utils.py    From PonyConf with Apache License 2.0 5 votes vote down vote up
def markdown_to_html(md):
    html = markdown(md)
    allowed_tags = bleach.ALLOWED_TAGS + ['p', 'pre', 'span' ] + ['h%d' % i for i in range(1, 7) ]
    html = bleach.clean(html, tags=allowed_tags)
    return mark_safe(html) 
Example #26
Source File: config.py    From django-baton with MIT License 5 votes vote down vote up
def get_config(key):
    safe = ['SITE_HEADER', 'COPYRIGHT', 'POWERED_BY', ]
    user_settings = getattr(settings, 'BATON', None)

    if user_settings is None:
        value = default_config.get(key, None)
    else:
        value = user_settings.get(key, default_config.get(key, None))

    if key in safe:
        return mark_safe(value)

    return value 
Example #27
Source File: blog_tags.py    From blog with Apache License 2.0 5 votes vote down vote up
def my_highlight(text, q):
    """自定义标题搜索词高亮函数,忽略大小写"""
    if len(q) > 1:
        try:
            text = re.sub(q, lambda a: '<span class="highlighted">{}</span>'.format(a.group()),
                          text, flags=re.IGNORECASE)
            text = mark_safe(text)
        except:
            pass
    return text 
Example #28
Source File: blog_tags.py    From blog with Apache License 2.0 5 votes vote down vote up
def get_active():
    """"获取活跃的友情链接"""
    text = Activate.objects.filter(is_active=True)
    if text:
        text = text[0].text
    else:
        text = ''
    return mark_safe(text)


# 获取归档文章查询集 
Example #29
Source File: factory.py    From Disfactory with MIT License 5 votes vote down vote up
def image_show(self, obj):
        return mark_safe(f'<img src="{obj.image_path}" style="max-width:500px; height:auto"/>') 
Example #30
Source File: jinja2.py    From intake with MIT License 5 votes vote down vote up
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)