def json_context(context, raise_error=False):
"""Generate a JS <script> tag from context
Serializes ``context["json_context"]`` into JSON and generates a JS
script to attach it to ``window.context``
If ``raise_error`` is False, values in context that are not
JSON serialisable will be converted to string. Otherwise, it
raises TypeError
:param context: Current view context
:param raise_error: Control whether to raise an error on non-JSON serialisable values
:return: ``<script>window.context = {<context["json_context"]>}</script>``
"""
if not context.get("json_context"):
return ""
json_default = None if raise_error else lambda obj: str(obj)
json_dump = json.dumps(context["json_context"], default=json_default)
return mark_safe("<script>window.context = %s;</script>" % json_dump)
python类mark_safe()的实例源码
def _items(self, record):
for field_name, _ in self.get_fields():
# Does the field_name refer to an aggregation column or is
# it an attribute of this instance?
try:
attr_field = getattr(self, field_name)
except AttributeError:
# The field is a record element
ret = record.get(field_name)
formatting_func = self.get_formatting().get(field_name)
if formatting_func is not None:
try:
ret = formatting_func(ret)
except (TypeError, ValueError):
pass
else:
# The view class has an attribute with this field_name
if callable(attr_field):
ret = attr_field(record)
if getattr(attr_field, 'allow_tags', False):
ret = mark_safe(ret)
yield ret
def website_link(page):
"""Link to the Page on website"""
if not page:
return None
url = page.url
url_parts = url.split('/')
if len(url_parts) <= 1:
styled_url = page.url
else:
for i in (-1, -2):
if url_parts[i]:
url_parts[i] = \
'<span style="font-weight: bold">{0}</span>'.format(
url_parts[i]
)
break
styled_url = '/'.join(url_parts)
return mark_safe(
'<a href="{url}" style="font-weight: normal;">{text}</a>'.format(
url=url, text='{url} »'.format(url=styled_url)
)
)
def format_user(user, format='full'):
if format == 'full':
full_name = conditional_escape(user.get_full_name())
username = conditional_escape(user.username)
result = u'{0} <span class="user-username">({1})</span>'.format(
full_name, username)
elif format == 'name':
result = conditional_escape(user.get_full_name())
elif format == 'username':
result = conditional_escape(user.username)
elif format == 'email':
return u'{0} ({1})'.format(user.get_full_name(), user.username)
else:
raise ValueError("Invalid format for format_user")
return mark_safe(result)
def render(self, context):
self.filter_expression.var.translate = not self.noop
if self.message_context:
self.filter_expression.var.message_context = (
self.message_context.resolve(context))
output = self.filter_expression.resolve(context)
value = render_value_in_context(output, context)
# Restore percent signs. Percent signs in template text are doubled
# so they are not interpreted as string format flags.
is_safe = isinstance(value, SafeData)
value = value.replace('%%', '%')
value = systemtext(value, group=self.group, default=self.default)
value = mark_safe(value) if is_safe else value
if self.asvar:
context[self.asvar] = value
return ''
else:
return value
def render_alert(content, alert_type=None, dismissable=True):
"""
Render a Bootstrap alert
"""
button = ''
if not alert_type:
alert_type = 'info'
css_classes = ['alert', 'alert-' + text_value(alert_type)]
if dismissable:
css_classes.append('alert-dismissable')
button = '<button type="button" class="close" ' + \
'data-dismiss="alert" aria-hidden="true">×</button>'
button_placeholder = '__BUTTON__'
return mark_safe(render_tag(
'div',
attrs={'class': ' '.join(css_classes)},
content=button_placeholder + text_value(content),
).replace(button_placeholder, button))
def render_field_and_label(
field, label, field_class='', label_for=None, label_class='',
layout='', **kwargs):
"""
Render a field with its label
"""
if layout == 'horizontal':
if not label_class:
label_class = get_bootstrap_setting('horizontal_label_class')
if not field_class:
field_class = get_bootstrap_setting('horizontal_field_class')
if not label:
label = mark_safe(' ')
label_class = add_css_class(label_class, 'control-label')
html = field
if field_class:
html = '<div class="{klass}">{html}</div>'.format(
klass=field_class, html=html)
if label:
html = render_label(
label, label_for=label_for, label_class=label_class) + html
return html
def url_replace_param(url, name, value):
"""
Replace a GET parameter in an URL
"""
url_components = urlparse(force_str(url))
params = parse_qs(url_components.query)
if value is None:
del params[name]
else:
params[name] = value
return mark_safe(urlunparse([
url_components.scheme,
url_components.netloc,
url_components.path,
url_components.params,
urlencode(params, doseq=True),
url_components.fragment,
]))
def get_search_result_list(product_list):
"""
????????
:param product_list:
:return:
"""
res = ""
if product_list:
for index in range(len(product_list)):
if index == 0:
res = ' <li class="active"><a id="set_click" href="javascript:;" onclick="get_plot(%s,this)">%s</a></li>' % (product_list[index].object.p_id,product_list[index].object.p_title)
else:
res += ' <li><a href="javascript:;" onclick="get_plot(%s,this)">%s</a></li>' % (product_list[index].object.p_id,product_list[index].object.p_title)
else:
res = '<li><a href="javascript:void(0);">????????</a></>'
return mark_safe(res)
def _format_callback(self, obj, user, admin_site, perms_needed):
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 = get_delete_permission(opts)
if not user.has_perm(p):
perms_needed.add(opts.verbose_name)
# Display a link to the admin page.
return mark_safe('%s: <a href="%s">%s</a>' %
(escape(capfirst(opts.verbose_name)),
admin_url,
escape(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))
def paginator_number(cl, i):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return mark_safe(
'<li class="disabled"><a href="#" onclick="return false;">..'
'.</a></li>')
elif i == cl.page_num:
return mark_safe(
'<li class="active"><a href="">%d</a></li> ' % (i + 1))
else:
return mark_safe('<li><a href="%s"%s>%d</a></li> ' % (
escape(cl.get_query_string({PAGE_VAR: i})),
(i == cl.paginator.num_pages - 1 and ' class="end"' or ''),
i + 1))
def headers_handler(result_headers, cl):
"""
Adds field name to css class, so we can style specific columns
"""
# field = cl.list_display.get()
attrib_key = 'class_attrib'
for i, header in enumerate(result_headers):
field_name = cl.list_display[i]
if field_name == 'action_checkbox':
continue
if not attrib_key in header:
header[attrib_key] = mark_safe(' class=""')
pattern = 'class="'
if pattern in header[attrib_key]:
replacement = '%s%s-column ' % (pattern, field_name)
header[attrib_key] = mark_safe(
header[attrib_key].replace(pattern, replacement))
return result_headers
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 self.is_initial(value):
template = self.template_with_initial
substitutions.update(self.get_template_substitution_values(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)
def render(self, name, value, attrs=None):
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id')
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
def render(self, name, value, attrs):
encoded = value
final_attrs = self.build_attrs(attrs)
if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
else:
try:
hasher = identify_hasher(encoded)
except ValueError:
summary = mark_safe("<strong>%s</strong>" % ugettext(
"Invalid password format or unknown hashing algorithm."))
else:
summary = format_html_join('',
"<strong>{}</strong>: {} ",
((ugettext(key), value)
for key, value in hasher.safe_summary(encoded).items())
)
return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(template.render({'flatpage': f}, request))
return response
def load_map_js(self):
"""
Returns JavaScript containing all of the loading routines for each
map in this set.
"""
result = []
for dom_id, gmap in zip(self.dom_ids, self.maps):
# Backup copies the GoogleMap DOM id and template attributes.
# They are overridden on each GoogleMap instance in the set so
# that only the loading JavaScript (and not the header variables)
# is used with the generated DOM ids.
tmp = (gmap.template, gmap.dom_id)
gmap.template = self.map_template
gmap.dom_id = dom_id
result.append(gmap.js)
# Restoring the backup values.
gmap.template, gmap.dom_id = tmp
return mark_safe(''.join(result))
def render(self, name, value, attrs=None):
if self.is_localized:
self.widget.is_localized = self.is_localized
value = value or []
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id')
for i in range(max(len(value), self.size)):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(self.widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
def localize(value, use_l10n=None):
"""
Checks if value is a localizable type (date, number...) and returns it
formatted as a string using current locale format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if isinstance(value, bool):
return mark_safe(six.text_type(value))
elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
return number_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.datetime):
return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
elif isinstance(value, datetime.date):
return date_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.time):
return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
else:
return value
def format_html_join(sep, format_string, args_generator):
"""
A wrapper of format_html, for the common case of a group of arguments that
need to be formatted using the same format string, and then joined using
'sep'. 'sep' is also passed through conditional_escape.
'args_generator' should be an iterator that returns the sequence of 'args'
that will be passed to format_html.
Example:
format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
for u in users))
"""
return mark_safe(conditional_escape(sep).join(
format_html(format_string, *tuple(args))
for args in args_generator))
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 self.is_initial(value):
template = self.template_with_initial
substitutions.update(self.get_template_substitution_values(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)
def render(self, name, value, attrs=None):
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id')
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
def render(self, name, value, attrs):
encoded = value
final_attrs = self.build_attrs(attrs)
if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
else:
try:
hasher = identify_hasher(encoded)
except ValueError:
summary = mark_safe("<strong>%s</strong>" % ugettext(
"Invalid password format or unknown hashing algorithm."
))
else:
summary = format_html_join(
'', '<strong>{}</strong>: {} ',
((ugettext(key), value) for key, value in hasher.safe_summary(encoded).items())
)
return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated:
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(template.render({'flatpage': f}, request))
return response
def load_map_js(self):
"""
Returns JavaScript containing all of the loading routines for each
map in this set.
"""
result = []
for dom_id, gmap in zip(self.dom_ids, self.maps):
# Backup copies the GoogleMap DOM id and template attributes.
# They are overridden on each GoogleMap instance in the set so
# that only the loading JavaScript (and not the header variables)
# is used with the generated DOM ids.
tmp = (gmap.template, gmap.dom_id)
gmap.template = self.map_template
gmap.dom_id = dom_id
result.append(gmap.js)
# Restoring the backup values.
gmap.template, gmap.dom_id = tmp
return mark_safe(''.join(result))
def render(self, name, value, attrs=None):
if self.is_localized:
self.widget.is_localized = self.is_localized
value = value or []
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id')
for i in range(max(len(value), self.size)):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(self.widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
def label_tag(self):
classes = []
contents = conditional_escape(force_text(self.field.label))
if self.is_checkbox:
classes.append('vCheckboxLabel')
if self.field.field.required:
classes.append('required')
if not self.is_first:
classes.append('inline')
attrs = {'class': ' '.join(classes)} if classes else {}
# checkboxes should not have a label suffix as the checkbox appears
# to the left of the label.
return self.field.label_tag(
contents=mark_safe(contents), attrs=attrs,
label_suffix='' if self.is_checkbox else None,
)
def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
# it's called "original" because it will be replaced by a copy
attrs['class'] = 'hstore-original-textarea'
# get default HTML from AdminTextareaWidget
html = super(BaseAdminHStoreWidget, self).render(name, value, attrs)
# prepare template context
template_context = Context({
'field_name': name,
'STATIC_URL': settings.STATIC_URL,
'use_svg': django.VERSION >= (1, 9), # use svg icons if django >= 1.9
})
# get template object
template = get_template('happenings/hstore_%s_widget.html' % self.admin_style)
# render additional html
additional_html = template.render(template_context)
# append additional HTML and mark as safe
html = html + additional_html
html = mark_safe(html)
return html
def render(self, name, value, attrs=None):
# get default HTML from AdminTextareaWidget
html = super(RecurringEventWidget, self).render(name, value, attrs)
if '__prefix__' in name:
return mark_safe(html)
data = {
"url": reverse('admin:happenings_get_occurrences'),
"field_id": attrs['id'],
"date_field": attrs['id'].replace(self.text_field, self.start_date_field)
}
additional_html = self.js_tmpl % data
# append additional HTML and mark as safe
html = html + additional_html
html = mark_safe(html)
return html
def reset_captcha(self):
"""Generate new question and valid token for it, reset previous answer
if any.
"""
q, a = self._generate_captcha()
expires = time.time() + \
getattr(settings, 'CAPTCHA_EXPIRES_SECONDS', 60*60)
token = self._make_token(q, a, expires)
self.initial['captcha_token'] = token
self._plain_question = q
# reset captcha fields for bound form
if self.data:
def _reset():
self.data['captcha_token'] = token
self.data['captcha_answer'] = ''
if hasattr(self.data, '_mutable') and not self.data._mutable:
self.data._mutable = True
_reset()
self.data._mutable = False
else:
_reset()
self.fields['captcha_answer'].label = mark_safe(self.knotty_question)