我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.html.conditional_escape()。
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_option(self, selected_choices, option_value, option_label): option_value = force_text(option_value) other_html = (u' selected="selected"' if option_value in selected_choices else '') if callable(self.transform_html_attrs): html_attrs = self.transform_html_attrs(option_label) other_html += flatatt(html_attrs) if not isinstance(option_label, (six.string_types, Promise)): for data_attr in self.data_attrs: data_value = html.conditional_escape( force_text(getattr(option_label, data_attr, ""))) other_html += ' data-%s="%s"' % (data_attr, data_value) if callable(self.transform): option_label = self.transform(option_label) return u'<option value="%s"%s>%s</option>' % ( html.escape(option_value), other_html, html.conditional_escape(force_text(option_label)))
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 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): # Prepare values attrs = self.build_attrs(attrs, name=name) if not value: value = '' options = getattr(settings, 'MARKEDIT_DEFAULT_SETTINGS', {}) if 'options' in attrs: options = self._eval_value(attrs['options'], {}) del attrs['options'] # Render widget to HTML t = loader.get_template('markedit/ui.html') c = Context({ 'attributes': self._render_attrs(attrs), 'value': conditional_escape(force_unicode(value)), 'id': attrs['id'], 'options': options, }) return t.render(c)
def _get_new_field_html(self, field_name): try: f, attr, value = lookup_field(field_name, self.org_obj, self) except (AttributeError, ObjectDoesNotExist): return EMPTY_CHANGELIST_VALUE else: allow_tags = False if f is None: allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True text = boolean_icon(value) else: text = smart_text(value) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(self.org_obj, f.name) if field_val is None: text = EMPTY_CHANGELIST_VALUE else: text = field_val else: text = display_for_field(value, f) return mark_safe(text) if allow_tags else conditional_escape(text)
def _get_new_field_html(self, field_name): try: f, attr, value = lookup_field(field_name, self.org_obj, self) except (AttributeError, ObjectDoesNotExist): return EMPTY_CHANGELIST_VALUE else: allow_tags = False if f is None: allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True text = boolean_icon(value) else: text = smart_unicode(value) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(self.org_obj, f.name) if field_val is None: text = EMPTY_CHANGELIST_VALUE else: text = field_val else: text = display_for_field(value, f) return mark_safe(text) if allow_tags else conditional_escape(text)
def test_doesnt_show_nonlive_partners(self): county = models.County.objects.first() live_org = auth_models.Organization( name='Starfleet', slug='starfleet', county=county, is_receiving_agency=True, is_live=True, ) not_live_org = auth_models.Organization( name="Jem'Hadar", slug='jem-hadar', county=county, is_receiving_agency=True, is_live=False, ) live_org.save() not_live_org.save() response = self.client.get(reverse('intake-partner_list')) self.assertContains( response, html_utils.conditional_escape(live_org.get_absolute_url())) self.assertNotContains( response, html_utils.conditional_escape(not_live_org.get_absolute_url()))
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.rel, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f) return conditional_escape(result_repr)
def test_markup(self): rr = attributes.ResourceReference() self.assertEqual(rr.to_markup(None), '') from chroma_core.models import StorageResourceRecord resource = StorageResourceRecord.objects.get(id = self.record_pk).to_resource() markup = rr.to_markup(resource) self.assertEqual(markup, conditional_escape(resource.get_label())) record = StorageResourceRecord.objects.get(pk = self.record_pk) record.alias = 'test alias' record.save() markup = rr.to_markup(resource) self.assertEqual(markup, conditional_escape('test alias'))
def to_markup(self, value): from chroma_core.models import StorageResourceRecord if value is None: return "" record = StorageResourceRecord.objects.get(pk = value._handle) if record.alias: name = record.alias else: name = value.get_label() from django.utils.html import conditional_escape name = conditional_escape(name) from django.utils.safestring import mark_safe return mark_safe("%s" % name)
def render(self, name, value, attrs=None): if value is None: value = "" if VERSION < (1, 11): final_attrs = self.build_attrs(attrs, name=name) else: 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)
def render(self, name, value, attrs=None): if value is None: value = '' extra_attrs = dict() extra_attrs['type'] = self.input_type extra_attrs['name'] = name input_attrs = self.build_attrs(attrs, extra_attrs) if value != '': # Only add the 'value' attribute if a value is non-empty. input_attrs['value'] = force_text(self._format_value(value)) input_attrs = {key: conditional_escape(val) for key, val in input_attrs.items()} if not self.picker_id: self.picker_id = (input_attrs.get('id', '') + '_pickers').replace(' ', '_') self.div_attrs['id'] = self.picker_id picker_id = conditional_escape(self.picker_id) div_attrs = {key: conditional_escape(val) for key, val in self.div_attrs.items()} icon_attrs = {key: conditional_escape(val) for key, val in self.icon_attrs.items()} html = self.html_template % dict(div_attrs=flatatt(div_attrs), input_attrs=flatatt(input_attrs), icon_attrs=flatatt(icon_attrs)) if self.options: js = self.js_template % dict(picker_id=picker_id, options=json_dumps(self.options or {})) else: js = '' return mark_safe(force_text(html + js))
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = widgets.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) output.append(u'<label class="%s"%s>%s %s</label>' % (self.label_class, label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): if value is None: value = "" if VERSION < (1, 11): final_attrs = self.build_attrs(attrs, name=name) else: final_attrs = self.build_attrs(attrs, {'name': name}) final_attrs = self.build_attrs(final_attrs, self.attrs) 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)
def get_template_substitution_values(self, value): """ Return value-related substitutions. """ return { 'initial': conditional_escape(value), 'initial_url': conditional_escape(value.url), }
def label_tag(self, contents=None, attrs=None, label_suffix=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. label_suffix allows overriding the form's label_suffix. """ contents = contents or self.label if label_suffix is None: label_suffix = (self.field.label_suffix if self.field.label_suffix is not None else self.form.label_suffix) # Only add the suffix if the label does not end in punctuation. # Translators: If found as last label character, these punctuation # characters will prevent the default label_suffix to be appended to the label if label_suffix and contents and contents[-1] not in _(':?.!'): contents = format_html('{}{}', contents, label_suffix) widget = self.field.widget id_ = widget.attrs.get('id') or self.auto_id if id_: id_for_label = widget.id_for_label(id_) if id_for_label: attrs = dict(attrs or {}, **{'for': id_for_label}) if self.field.required and hasattr(self.form, 'required_css_class'): attrs = attrs or {} if 'class' in attrs: attrs['class'] += ' ' + self.form.required_css_class else: attrs['class'] = self.form.required_css_class attrs = flatatt(attrs) if attrs else '' contents = format_html('<label{}>{}</label>', attrs, contents) else: contents = conditional_escape(contents) return mark_safe(contents)
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 contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): warnings.warn( "Deprecated allow_tags attribute used on %s. " "Use django.utils.safestring.format_html(), " "format_html_join(), or mark_safe() instead." % attr, RemovedInDjango20Warning ) result_repr = mark_safe(value) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)