Here are the examples of the python api django.utils.html.conditional_escape taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
150 Examples
3
Example 1
def __unicode__(self):
if 'id' in self.attrs:
label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
return mark_safe(u'<label%s>%s %s</label>' % (label_for, self.tag(), choice_label))
3
Example 2
def __init__(self, html, media=None, cacheable=True, cache_timeout=DEFAULT_TIMEOUT):
self.html = conditional_escape(html) # enforce consistency
self.media = media or ImmutableMedia.empty_instance
# Mainly used internally for the _render_items():
# NOTE: this is the only place where 'cachable' was written was 'cacheable'
self.cacheable = cacheable
self.cache_timeout = cache_timeout or DEFAULT_TIMEOUT
3
Example 3
def label_tag(self, contents=None, attrs=None):
"""
Wraps the given contents in a <label>, if the field has an ID attribute.
contents should be 'mark_safe'd to avoid HTML escaping. If contents
aren't given, uses the field's HTML-escaped label.
If attrs are given, they're used as HTML attributes on the <label> tag.
"""
contents = contents or self.label
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
if id_:
attrs = attrs and flatatt(attrs) or ''
contents = format_html('<label for="{0}"{1}>{2}</label>',
widget.id_for_label(id_), attrs, contents
)
else:
contents = conditional_escape(contents)
return mark_safe(contents)
3
Example 4
def render(self, name, value, attrs=None):
content = ''
if value is not None:
content = value
if self.show_text is not None:
content = self.show_text
final_attrs = self.build_attrs(attrs)
# TODO: Django >1.4:
# return format_html('<span{0}>{1}</span>',
# flatatt(final_attrs),
# force_text(content))
return mark_safe('<span{0}>{1}</span>'.format(
conditional_escape(flatatt(final_attrs)),
conditional_escape(force_text(content))
))
3
Example 5
def as_ul(self):
if not self: return u''
error_list = []
for k, v in self.items():
if k == NON_FIELD_ERRORS:
k = ''
error_list.append(u'%s%s' % (k, conditional_escape(force_unicode(v))))
return mark_safe(u'<ul class="errorlist">%s</ul>'
% ''.join([u'<li>%s</li>' % e for e in error_list]))
3
Example 6
Project: oioioi Source File: __init__.py
def make_html_link(href, name, method='GET', extra_attrs=None):
if method == 'GET':
attrs = {'href': href}
elif method == 'POST':
attrs = {'data-post-url': href, 'href': '#'}
if not extra_attrs:
extra_attrs = {}
attrs.update(extra_attrs)
return mark_safe(u'<a %s>%s</a>' % (flatatt(attrs),
conditional_escape(force_unicode(name))))
3
Example 7
def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
return {
'initial': conditional_escape(value),
'initial_url': conditional_escape(value.url),
}
3
Example 8
def _get_level_indicator(self, obj):
level = getattr(obj, obj._mptt_meta.level_attr) - self.base_level
if level > 0:
return mark_safe(conditional_escape(self.level_indicator) * level)
else:
return ''
3
Example 9
def get_template_context(self, attrs, value):
return {
'attrs': flatatt(attrs),
'body': conditional_escape(force_unicode(value)),
'id': attrs['id'],
'show_preview': self.show_preview,
'preview_url': self.preview_url
}
3
Example 10
def render(self, context=None, request=None):
if context is None:
context = {}
else:
context = {k: conditional_escape(v) for k, v in context.items()}
if request is not None:
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
return self.safe_substitute(context)
3
Example 11
Project: cgstudiomap Source File: base.py
def render_value_in_context(value, context):
"""
Converts any value to a string to become part of a rendered template. This
means escaping, if required, and conversion to a unicode object. If value
is a string, it is expected to have already been translated.
"""
value = template_localtime(value, use_tz=context.use_tz)
value = localize(value, use_l10n=context.use_l10n)
value = force_text(value)
if ((context.autoescape and not isinstance(value, SafeData)) or
isinstance(value, EscapeData)):
return conditional_escape(value)
else:
return value
3
Example 12
def render(self, name, value, attrs=None):
if value is None:
value = ""
final_attrs = self.build_attrs(attrs, name=name)
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# Compatibility fix:
# see https://github.com/timmyomahony/django-pagedown/issues/42
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"show_preview": self.show_preview,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
3
Example 13
def render_label(self):
bits = []
if self.icon:
bits.append('<i class="%s"></i> ' % self.icon)
bits.append(conditional_escape(self.text))
return "".join(force_text(bit) for bit in bits)
3
Example 14
def get_fields_html():
# TODO: Django >1.4:
# reutrn format_html_join('\n', '<option value="{0}">{1}</option>',
# (df for df in dffr.get_as_choices()))
return mark_safe(
'\n'.join(
'<option value="{0}">{1}</option>'.format(
conditional_escape(df[0]),
conditional_escape(df[1])
)
for df in dffr.get_as_choices()
)
)
3
Example 15
Project: pycontw2016 Source File: utils.py
def html_join(sep, sequence):
"""Similar to str.join, but passes the separator and all elements in the
sequence through conditional_escape, and calls 'mark_safe' on the result.
This function should be used instead of str.join to build up small HTML
fragments.
"""
sep_safe = conditional_escape(sep)
return mark_safe(sep_safe.join(conditional_escape(e) for e in sequence))
3
Example 16
def label_tag(self, contents=None, attrs=None):
"""
'mark_safe'd to avoid HTML escaping
Wraps the given contents in a <label>, if the field has an ID attribute.
contents should be 'mark_safe'd to avoid HTML escaping. If contents
aren't given, uses the field's HTML-escaped label.
If attrs are given, they're used as HTML attributes on the <label> tag.
"""
contents = contents or conditional_escape(self.label)
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
if id_:
attrs = attrs and flatatt(attrs) or ''
contents = format_html('<label for="{0}"{1}>{2}</label>',
widget.id_for_label(id_), attrs, contents
)
return mark_safe(contents)
3
Example 17
def render(self, name, value, *args, **kwargs):
(extra, value_is_from_database) = find_extra_attrs(value)
widget_html = self.widget.render(name, value, *args, **kwargs)
if extra and value_is_from_database:
return mark_safe(u'<div class="localized catalog-has-different-data">%s <small><a class="extra-catalog-data" title="%s">\u2234\u207A</a></small></div>' % (widget_html, conditional_escape(extra)))
elif not value_is_from_database:
return mark_safe(u'<div class="localized">%s <small>\u2234\u00B0</small></div>' % widget_html)
return mark_safe(u'<div class="localized">%s <small>\u2234</small></div>' % widget_html)
3
Example 18
def __init__(self, *args, **kwargs):
self.fields = list(args)
if not hasattr(self, 'attrs'):
self.attrs = {}
if 'css_class' in kwargs:
if 'class' in self.attrs:
self.attrs['class'] += " %s" % kwargs.pop('css_class')
else:
self.attrs['class'] = kwargs.pop('css_class')
self.wrapper_class = kwargs.pop('wrapper_class', None)
self.template = kwargs.pop('template', self.template)
# We use kwargs as HTML attributes, turning data_id='test' into data-id='test'
self.attrs.update(dict([(k.replace('_', '-'), conditional_escape(v)) for k, v in kwargs.items()]))
3
Example 19
@register.filter(is_safe=True, needs_autoescape=True)
def join(value, arg, autoescape=None):
"""
Joins a list with a string, like Python's ``str.join(list)``.
"""
value = map(force_text, value)
if autoescape:
value = [conditional_escape(v) for v in value]
try:
data = conditional_escape(arg).join(value)
except AttributeError: # fail silently but nicely
return value
return mark_safe(data)
3
Example 20
Project: django-fluent-contents Source File: markers.py
def wrap_contentitem_output(html, contentitem):
return mark_safe('<div class="cp-editable-contentitem" data-itemtype="{itemtype}" data-item-id="{id}">' \
'{html}' \
'</div>\n'.format(
html=conditional_escape(html),
itemtype=contentitem.__class__.__name__, # Same as ContentPlugin.type_name
id=contentitem.id,
))
3
Example 21
@property
def label(self):
text = mark_safe(
self.text) if self.allow_tags else conditional_escape(self.text)
if force_unicode(text) == '':
text = mark_safe(' ')
for wrap in self.wraps:
text = mark_safe(wrap % text)
return text
3
Example 22
def render(self, name=None, value=None, attrs=None, choices=()):
name = name or self.name
value = value or self.value
attrs = attrs or self.attrs
attrs['class'] = attrs.get('class', '').replace('form-control', '')
if 'id' in self.attrs:
label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
if attrs.get('inline', False):
return mark_safe(u'<label%s class="radio-inline">%s %s</label>' % (label_for, self.tag(), choice_label))
else:
return mark_safe(u'<div class="radio"><label%s>%s %s</label></div>' % (label_for, self.tag(), choice_label))
3
Example 23
def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
bname = os.path.basename(value.name)
return {
'initial': conditional_escape(bname),
'initial_url': conditional_escape(value.url),
}
3
Example 24
Project: wateronmars Source File: html_sanitizers.py
def auto_esc(text,autoescape):
"""
Escape or not (just to factorize a little bit of code).
"""
if autoescape:
return conditional_escape(text)
else:
return text
3
Example 25
Project: snowy Source File: __init__.py
def render(self, name, value, attrs=None):
final_attrs = self.build_attrs(attrs)
error = final_attrs.get('error', None)
html = captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY, error=error)
options = u',\n'.join([u'%s: "%s"' % (k, conditional_escape(v)) \
for k, v in final_attrs.items() if k in self.options])
return mark_safe("""<script type="text/javascript">
var RecaptchaOptions = {
%s
};
</script>
%s
""" % (options, html))
3
Example 26
Project: tri.table Source File: __init__.py
def default_cell_formatter(table, column, row, value, **_):
"""
:type column: tri.table.BoundColumn
"""
formatter = _cell_formatters.get(type(value))
if formatter:
value = formatter(table=table, column=column, row=row, value=value)
if value is None:
return ''
return conditional_escape(value)
3
Example 27
Project: wagtail Source File: wagtailadmin_tags.py
@register.simple_tag
def replace_page_param(query, page_number, page_key='p'):
"""
Replaces ``page_key`` from query string with ``page_number``.
"""
return conditional_escape(replace_page_in_query(query, page_number, page_key))
3
Example 28
def _forbidden_response(request, visible_to):
"""
A nicer forbidden message that says why, and gently suggests that anonymous users log in.
"""
error = 'Not allowed to view this page. It is visible only to %s in this course.' % (visible_to,)
errormsg_template = '<strong>You are not currently logged in</strong>. You may be able to view this page if you <a href="%s">log in</a>'
errormsg = None
if not request.user.is_authenticated():
url = conditional_escape(settings.LOGIN_URL + '?next=' + request.get_full_path())
errormsg = mark_safe(errormsg_template % (url))
return HttpError(request, status=403, title="Forbidden", error=error, errormsg=errormsg)
3
Example 29
@register.filter(is_safe=True, needs_autoescape=True)
def join(value, arg, autoescape=True):
"""
Joins a list with a string, like Python's ``str.join(list)``.
"""
value = map(force_text, value)
if autoescape:
value = [conditional_escape(v) for v in value]
try:
data = conditional_escape(arg).join(value)
except AttributeError: # fail silently but nicely
return value
return mark_safe(data)
3
Example 30
@register.filter(is_safe=True, needs_autoescape=True)
def join(value, arg, autoescape=None):
"""
Joins a list with a string, like Python's ``str.join(list)``.
"""
value = map(force_text, value)
if autoescape:
value = [conditional_escape(v) for v in value]
try:
data = conditional_escape(arg).join(value)
except AttributeError: # fail silently but nicely
return value
return mark_safe(data)
3
Example 31
Project: dj-dynamic-forms Source File: admin.py
def format_output(self, rendered_widgets, id_):
output = []
i = 0
for n, (r, w) in six.moves.zip(self.option_names, rendered_widgets):
# TODO: Django >1.4:
#output.append(format_html('<label for="{0}_{1}">{2}:</label>{3}',
# w.id_for_label(id_), i, n, r))
output.append(
mark_safe('<label for="{0}_{1}">{2}:</label>{3}'.format(
conditional_escape(w.id_for_label(id_)),
conditional_escape(i),
conditional_escape(n),
conditional_escape(r)
)))
i += 1
return mark_safe('<div style="display:inline-block;">' +
('<br />\n'.join(output)) + '</div>')
3
Example 32
def get_rendered_output(self):
body = u"".join(conditional_escape(smart_text(piece)) for piece in self.output)
styles = self.styles
extrahead = (self.extra_header or u"")
if self.inline:
template = self.INLINE_TEMPLATE
else:
template = self.TEMPLATE
html = template % {"title": self.title, "body": body, "style": styles, "extrahead": extrahead}
if not self.inline:
html = html.encode("UTF-8")
return html
3
Example 33
def render_option(self, selected_choices, option_value, option_label):
option_value = force_unicode(option_value)
selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
return u'<option value="%s"%s>%s</option>' % (
escape(option_value), selected_html,
conditional_escape(force_unicode(option_label)))
3
Example 34
def label_tag(self, contents=None, attrs=None):
"""
Wraps the given contents in a <label>, if the field has an ID attribute.
contents should be 'mark_safe'd to avoid HTML escaping. If contents
aren't given, uses the field's HTML-escaped label.
If attrs are given, they're used as HTML attributes on the <label> tag.
"""
contents = contents or conditional_escape(self.label)
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
if id_:
attrs = attrs and flatatt(attrs) or ''
contents = format_html('<label for="{0}"{1}>{2}</label>',
widget.id_for_label(id_), attrs, contents
)
return mark_safe(contents)
3
Example 35
def render(self, name, value, attrs=None):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
textarea_widget = '<textarea%s>%s</textarea>' % (
flatatt(final_attrs),
conditional_escape(force_text(value)))
wid = final_attrs.get('id', 'unknown')
toolbar_widget = self.render_toolbar_widget(wid)
pos = wid.find('__prefix__')
if pos != -1:
js_widget = self.render_js_delay_widget(wid, pos)
else:
js_widget = self.render_js_init_widget(wid)
return mark_safe('<div style="display:inline-block">' +
toolbar_widget +
textarea_widget +
'</div>' +
js_widget)
3
Example 36
def user_full_name(self, instance):
if not instance.user:
instance = instance.programsubmission
if instance:
instance = instance.modelprogramsubmission
if instance:
return '(%s)' % (conditional_escape(force_unicode(
instance.model_solution.name)),)
return super(ModelSubmissionAdminMixin, self).user_full_name(instance)
3
Example 37
def join(value, arg, autoescape=None):
"""
Joins a list with a string, like Python's ``str.join(list)``.
"""
value = map(force_unicode, value)
if autoescape:
from django.utils.html import conditional_escape
value = [conditional_escape(v) for v in value]
try:
data = arg.join(value)
except AttributeError: # fail silently but nicely
return value
return mark_safe(data)
3
Example 38
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
self._set_config()
external_plugin_resources = [
[force_text(a), force_text(b), force_text(c)]
for a, b, c in self.external_plugin_resources]
return mark_safe(
render_to_string('custom_widget/ckeditor_widget.html', {
'final_attrs': flatatt(final_attrs),
'value': conditional_escape(force_text(value)),
'id': final_attrs['id'],
'config': json_encode(self.config),
'external_plugin_resources': json_encode(
external_plugin_resources)
}))
3
Example 39
Project: django Source File: base.py
def render_value_in_context(value, context):
"""
Converts any value to a string to become part of a rendered template. This
means escaping, if required, and conversion to a unicode object. If value
is a string, it is expected to have already been translated.
"""
value = template_localtime(value, use_tz=context.use_tz)
value = localize(value, use_l10n=context.use_l10n)
value = force_text(value)
if context.autoescape or isinstance(value, EscapeData):
return conditional_escape(value)
else:
return value
3
Example 40
def label_tag(self):
classes = []
contents = conditional_escape(force_text(self.field.label))
if self.is_checkbox:
classes.append('vCheckboxLabel')
else:
contents += ':'
if self.field.field.required:
classes.append('required')
if not self.is_first:
classes.append('inline')
attrs = classes and {'class': ' '.join(classes)} or {}
return self.field.label_tag(contents=mark_safe(contents), attrs=attrs)
3
Example 41
def flatatt(attrs):
"""
Taken from django.core.utils
Convert a dictionary of attributes to a single string.
The returned string will contain a leading space followed by key="value",
XML-style pairs. It is assumed that the keys do not need to be XML-escaped.
If the passed dictionary is empty, then return an empty string.
"""
return ''.join([' %s="%s"' % (k.replace('_', '-'), conditional_escape(v)) for k, v in attrs.items()])
3
Example 42
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)]
str_values = set([force_unicode(v) for v in value]) # Normalize to strings.
for option_value, option_label in chain(self.choices, choices):
option_value = force_unicode(option_value)
selected_html = (option_value in str_values) and ' selected="selected"' or ''
output.append(u'<option value="%s"%s>%s</option>' % (
escape(option_value), selected_html,
conditional_escape(force_unicode(option_label))))
output.append(u'</select>')
return mark_safe(u'\n'.join(output))
3
Example 43
Project: django-fluent-contents Source File: markers.py
def wrap_placeholder_output(html, placeholder):
return mark_safe('<div class="cp-editable-placeholder" id="cp-editable-placeholder-{slot}" data-placeholder-id="{id}" data-placeholder-slot="{slot}">' \
'{html}' \
'</div>\n'.format(
html=conditional_escape(html),
id=placeholder.id,
slot=placeholder.slot,
))
3
Example 44
@property
def val(self):
text = mark_safe(
self.text) if self.allow_tags else conditional_escape(self.text)
if force_unicode(text) == '' or text == 'None' or text == EMPTY_CHANGELIST_VALUE:
text = mark_safe(
'<span class="text-muted">%s</span>' % EMPTY_CHANGELIST_VALUE)
for wrap in self.wraps:
text = mark_safe(wrap % text)
return text
3
Example 45
Project: django-uturn Source File: uturn.py
def _do_uturn_param(request):
next = get_redirect_url(request)
if next:
attr = {
'param': conditional_escape(param_name()),
'value': conditional_escape(next)
}
f = "<input type='hidden' name='%(param)s' value='%(value)s'>" % attr
return mark_safe("<div style='display:none'>%s</div>" % f)
return ''
3
Example 46
def render(self, name, value, attrs=None):
if value is None: value = ''
value = force_unicode(value)
final_attrs = self.build_attrs(attrs, name=name)
return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs),
conditional_escape(force_unicode(value))))
3
Example 47
def render(self, context):
user = self.user_var.resolve(context)
display = user_display(user)
if self.as_var:
context[self.as_var] = display
return ""
return conditional_escape(display)
3
Example 48
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)
3
Example 49
def render_option(self, selected_choices, option_value, option_label):
option_value = smart_text(option_value)
attrs = flatatt(self.options_attributes.get(option_value, {}))
if option_value in selected_choices:
selected_html = u' selected="selected"'
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
return u'<option%s value="%s"%s>%s</option>' % (
attrs,
escape(option_value), selected_html,
conditional_escape(smart_text(option_label)))
3
Example 50
def render_option(self, selected_choices, option_value, option_label):
option_value = force_unicode(option_value)
selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
disabled_html = (int(option_value) in self.disabled_choices) and u' disabled="disabled"' or ''
return u'<option value="%s"%s>%s</option>' % (
escape(option_value), selected_html + disabled_html,
conditional_escape(force_unicode(option_label)))