本文整理汇总了Python中django.utils.html.mark_safe方法的典型用法代码示例。如果您正苦于以下问题:Python html.mark_safe方法的具体用法?Python html.mark_safe怎么用?Python html.mark_safe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.html
的用法示例。
在下文中一共展示了html.mark_safe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: photo_list
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
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)
示例2: test_format_html
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
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>")
),
"< Dangerous > <b>safe</b> < dangerous again <i>safe again</i>"
)
示例3: truncatesmart
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
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) + ' [...]')
示例4: formatmonth
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
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)
示例5: render_column
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
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 ""
示例6: video_tag
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
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)))
示例7: fontawesome_icon
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def fontawesome_icon(icon, title='', large=False, fixed=False, spin=False, li=False,
rotate=False, border=False, color=False):
return mark_safe('<i title="{title}" class="{prefix} {prefix}-{icon}{large}{fixed}{spin}{li}{rotate}{border}" {color}></i>'.format(
title=title,
prefix=getattr(settings, 'FONTAWESOME_PREFIX', 'fa'),
icon=icon,
large=' fa-lg' if large is True else '',
fixed=' fa-fw' if fixed else '',
spin=' fa-spin' if spin else '',
li=' fa-li' if li else '',
rotate=' fa-rotate-%s' % str(rotate) if rotate else '',
border=' fa-border' if border else '',
color='style="color:%s;"' % color if color else ''
))
示例8: render
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def render(self, name, value, attrs=None, renderer=None):
output = super(CustomMultipleInputWidget, self).render(name, value, attrs=attrs, renderer=renderer)
open_tag = '<div class="list-input" data-name="%s" data-min="%i" data-max="%i">' % (name, self.min, self.max)
return mark_safe(open_tag) + conditional_escape(output) + mark_safe('</div>')
示例9: student_photo
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def student_photo(request, emplid):
# confirm user's photo agreement
user = get_object_or_404(Person, userid=request.user.username)
can_access = False
if Role.objects_fresh.filter(person=user, role__in=['ADVS', 'ADVM']):
can_access = True
else:
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)))
# confirm user is an instructor of this student (within the last two years)
# TODO: cache past_semester to save the query?
past_semester = Semester.get_semester(datetime.date.today() - datetime.timedelta(days=730))
student_members = Member.objects.filter(offering__semester__name__gte=past_semester.name,
person__emplid=emplid, role='STUD').select_related('offering')
student_offerings = [m.offering for m in student_members]
instructor_of = Member.objects.filter(person=user, role='INST', offering__in=student_offerings)
can_access = (instructor_of.count() > 0)
if not can_access:
return ForbiddenResponse(request, 'You must be an instructor of this student.')
# get the photo
data, status = photo_for_view(emplid)
# return the photo
response = HttpResponse(data, content_type='image/jpeg')
response.status_code = status
response['Content-Disposition'] = 'inline; filename="%s.jpg"' % (emplid)
response['Cache-Control'] = 'private, max-age=300'
return response
示例10: render
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def render(self, context):
obj = self.obj.resolve(context)
#user = self.user.resolve(context)
debug = False
#if user and user.username == 'ggbaker':
# debug = True
if isinstance(obj, GradStudent):
gs = obj
else:
gs = obj.student
# if gs.program.unit.slug == 'cmpt' and not debug:
# return ''
if hasattr(obj, 'config') and SIMS_SOURCE in obj.config and obj.config[SIMS_SOURCE]:
tag = '<i class="fa fa-check sims_check_yes" title="Found in SIMS"></i>'
if debug:
tag += ' <span style="font-size: 65%%;">%s</span>' % \
(conditional_escape(json.dumps(obj.config[SIMS_SOURCE])))
elif isinstance(obj, Supervisor) and obj.supervisor_type == 'POT':
# these aren't in SIMS ever so don't complain
tag = ''
else:
tag = '<i class="fa fa-question sims_check_no" title="Not found in SIMS import"></i>'
return mark_safe(tag)
示例11: render
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def render(self, name, value, attrs=None):
if value is None:
value = ''
if attrs is None:
attrs = {}
# The widget displayed to the user
div_attrs = {'id': name,
'class': 'tinymce-editor',
'data-tinymce-use-media': self.with_media,
'data-tinymce-language-code': self.get_language()
}
div_html = '<div{}>{}</div>'.format(
flatatt(div_attrs),
force_text(value)
)
# The input used by django
attrs.update({'name': name, 'value': escape(value), 'type': 'hidden'})
input_attrs = self.build_attrs(attrs)
input_html = '<input{} />'.format(
flatatt(input_attrs)
)
html = '\n'.join([div_html, input_html])
return mark_safe(html)
示例12: plugin_point
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def plugin_point(context, name):
templates = [template_path(app, name) for app in apps]
result = ""
context = context.flatten()
for template in templates:
try:
t = get_template(template)
result += t.render(context, context['request'])
except TemplateDoesNotExist:
pass
return mark_safe(result)
示例13: render
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def render(self, context):
request = context.get("request", None)
if request:
tag_config = TagTypeSettings().get(self.tag_type)
if TagStrategy(request=request).should_include(self.tag_type, tag_config):
ctx = Tag.create_context(request=request, context=context)
if self.src:
if self.src.endswith(".html"):
return render_to_string(self.src, ctx)
elif self.src.endswith(".css"):
tag = BeautifulSoup("", "html.parser").new_tag("link")
tag["rel"] = "stylesheet"
tag["type"] = "text/css"
tag["href"] = static(self.src)
elif self.src.endswith(".js"):
tag = BeautifulSoup("", "html.parser").new_tag("script")
tag["type"] = "text/javascript"
tag["src"] = static(self.src)
return mark_safe(tag.decode())
output = self.nodelist.render(ctx)
return output
return ""
示例14: name_display
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
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
示例15: slugify_petitions
# 需要导入模块: from django.utils import html [as 别名]
# 或者: from django.utils.html import mark_safe [as 别名]
def slugify_petitions(apps, schema_editor):
Petition = apps.get_model('petition', 'Petition')
SlugModel = apps.get_model('petition', 'SlugModel')
for p in Petition.objects.all():
if p.slugmodel_set.count() == 0:
raw_title = html.unescape(mark_safe(strip_tags(p.title).strip()))
SlugModel.objects.create(slug=slugify(raw_title[:200]), petition=p)