Python django.utils.html.conditional_escape() Examples

The following are 30 code examples of django.utils.html.conditional_escape(). 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: widgets.py    From telemetry-analysis-service with Mozilla Public License 2.0 6 votes vote down vote up
def render(self, name, value, attrs=None):
        # render the hidden input first
        cachekey_field = super().render(name, value, attrs)

        # check if there is a cached file
        metadata = self.cache.metadata(value)
        if metadata is None:
            # if not, just return the hidden input
            return cachekey_field

        # or render the additional cached file
        return mark_safe(
            self.template_with_cachekey
            % {
                "file_name": conditional_escape(metadata["name"]),
                "cachekey_field": cachekey_field,
            }
        ) 
Example #2
Source File: widgets.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #3
Source File: visa_display.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def display_visas(person):
    visas = Visa.get_visas([person])
    if visas.count() > 1:
        result = '<a href="%s">More than one visa found</a>' % reverse('visas:list_all_visas', kwargs={'emplid':person.userid_or_emplid()})
        return mark_safe(result)

    elif visas.count() == 0:
        result = '<a href="%s">No visa found</a>' % reverse('visas:new_visa', kwargs={'emplid':person.userid_or_emplid()})
        return mark_safe(result)

    elif visas.count() == 1:
        visa = visas[0]

        result = ['<a href="', reverse('visas:edit_visa', kwargs={'visa_id': visa.id}), '" ',
                  e(add_visa_display_class(visa)),'>', e(visa.status),' valid from ', e(str(visa.start_date)), ' until ',
                  e(str(visa.end_date)), ' -- ', e(visa.get_validity()), '</a>']
        return mark_safe(''.join(result))

    else:
        return "Undefined visa error, please contact support." 
Example #4
Source File: editable.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: panel.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def settings_info():
    info = []
    info.append(('Deploy mode', settings.DEPLOY_MODE))
    info.append(('Database engine', settings.DATABASES['default']['ENGINE']))
    info.append(('Authentication Backends', settings.AUTHENTICATION_BACKENDS))
    info.append(('Cache backend', settings.CACHES['default']['BACKEND']))
    info.append(('Haystack engine', settings.HAYSTACK_CONNECTIONS['default']['ENGINE']))
    info.append(('Email backend', settings.EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_EMAIL') and settings.CELERY_EMAIL:
        info.append(('Celery email backend', settings.CELERY_EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_BROKER_URL'):
        info.append(('Celery broker', settings.CELERY_BROKER_URL.split(':')[0]))

    DATABASES = copy.deepcopy(settings.DATABASES)
    for d in DATABASES:
        if 'PASSWORD' in DATABASES[d]:
            DATABASES[d]['PASSWORD'] = '*****'
    info.append(('DATABASES',  mark_safe('<pre>'+escape(pprint.pformat(DATABASES))+'</pre>')))

    return info 
Example #6
Source File: editable.py    From CTF_AWD_Platform with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: editable.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: helpers.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: select.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def to_html(self, fieldsubmission=None):

        the_choices = [(k, v) for k, v in self.config.items() if k.startswith("choice_") and self.config[k]]
        the_choices = sorted(the_choices, key=lambda choice: (int) (re.findall(r'\d+', choice[0])[0]))

        initial = []

        if fieldsubmission:
            initial = fieldsubmission.data['info']

        display_values = [dict(the_choices)[str(i)] for i in initial]

        if display_values:
            output = '<ul>'

            for item in display_values:
                output += '<li>%s</li>' % escape(str(item))
            output += '</ul>'
        else:
            output = '<p class="empty">None selected</p>'

        return mark_safe(output) 
Example #10
Source File: editable.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #11
Source File: helpers.py    From bioforum with MIT License 6 votes vote down vote up
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 = linebreaksbr(value)
            else:
                if isinstance(f.remote_field, ManyToManyRel) and value is not None:
                    result_repr = ", ".join(map(str, value.all()))
                else:
                    result_repr = display_for_field(value, f, self.empty_value_display)
                result_repr = linebreaksbr(result_repr)
        return conditional_escape(result_repr) 
Example #12
Source File: editable.py    From django_OA with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #13
Source File: helpers.py    From bioforum with MIT License 6 votes vote down vote up
def label_tag(self):
        classes = []
        contents = conditional_escape(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,
        ) 
Example #14
Source File: form_display.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def label_display(field, prefix=''):
    out = []

    labelid = str(field.name)
    if prefix:
        labelid = prefix + '-' + labelid
    if isinstance(field.field.widget, (RadioSelect, SupervisorWidget)):
        labelid += '_0'

    out.append('<label for="id_%s">' % (labelid,))
    out.append(escape(field.label))
    out.append(':')
    if field.field.required or (hasattr(field.field, 'force_display_required') and field.field.force_display_required):
        out.append('&nbsp;' + required_icon)

    out.append('</label>')

    return mark_safe(''.join(out)) 
Example #15
Source File: form_display.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def field_display(field, safe=False):
    out = []
    if isinstance(field.field.widget, (forms.widgets.RadioSelect, forms.widgets.CheckboxSelectMultiple)):
        out.append('<div class="field radio">%s</div>' % (str(field)))
    else:
        out.append('<div class="field">%s</div>' % (str(field)))
    out.append(str(field.errors))

    if field.help_text:
        if isinstance(field.help_text, Promise):
            out.append('<div class="helptext">%s</div>' % (escape(field.help_text)))
        else:
            if safe:
                out.append('<div class="helptext">%s</div>' % (field.help_text))
            else:
                out.append('<div class="helptext">%s</div>' % (escape(field.help_text)))
    return mark_safe('\n'.join(out)) 
Example #16
Source File: models.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def get_owners_display(self, units):
        """
        HTML display of the owners list

        (some logic required since we want to link to faculty profiles if exists && permitted)
        """
        from django.utils.html import conditional_escape as escape
        from django.utils.safestring import mark_safe
        res = []
        for o in self.grantowner_set.all():
            p = o.person
            if Role.objects.filter(unit__in=units, role='FAC', person=p).exists():
                url = reverse('faculty:summary', kwargs={'userid': p.userid_or_emplid()})
                res.append('<a href="%s">%s</a>' %(escape(url), escape(o.person.name())))
            else:
                res.append(escape(o.person.name()))

        return mark_safe(', '.join(res)) 
Example #17
Source File: list.py    From django_OA with GNU General Public License v3.0 5 votes vote down vote up
def label(self):
        text = mark_safe(
            self.text) if self.allow_tags else conditional_escape(self.text)
        if force_text(text) == '':
            text = mark_safe('&nbsp;')
        for wrap in self.wraps:
            text = mark_safe(wrap % text)
        return text 
Example #18
Source File: multiselect.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def render_opt(self, selected_choices, option_value, option_label):
        option_value = force_text(option_value)
        return u'<option value="%s">%s</option>' % (
            escape(option_value), conditional_escape(force_text(option_label))), bool(option_value in selected_choices) 
Example #19
Source File: hooks.py    From pinax-forums with MIT License 5 votes vote down vote up
def parse(self, text):
        return conditional_escape(
            mark_safe(
                linebreaks(
                    urlize(
                        escape(text)
                    )
                )
            )
        ) 
Example #20
Source File: detail.py    From django_OA with GNU General Public License v3.0 5 votes vote down vote up
def val(self):
        text = mark_safe(
            self.text) if self.allow_tags else conditional_escape(self.text)
        if force_text(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 
Example #21
Source File: widgets.py    From django_OA with GNU General Public License v3.0 5 votes vote down vote up
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_text(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)) 
Example #22
Source File: multiselect.py    From myblog with GNU Affero General Public License v3.0 5 votes vote down vote up
def render_opt(self, selected_choices, option_value, option_label):
        option_value = force_text(option_value)
        return u'<option value="%s">%s</option>' % (
            escape(option_value), conditional_escape(force_text(option_label))), bool(option_value in selected_choices) 
Example #23
Source File: widgets.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
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, extra_attrs={'name': name})
        output = []
        # Normalize to strings
        str_values = set([force_text(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 = forms.CheckboxInput(
                final_attrs, check_test=lambda value: value in str_values)
            option_value = force_text(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_text(option_label))

            if final_attrs.get('inline', False):
                output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label))
            else:
                output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label))
        return mark_safe(u'\n'.join(output)) 
Example #24
Source File: widgets.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
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_text(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)) 
Example #25
Source File: detail.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def val(self):
        text = mark_safe(
            self.text) if self.allow_tags else conditional_escape(self.text)
        if force_text(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 
Example #26
Source File: list.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def label(self):
        text = mark_safe(
            self.text) if self.allow_tags else conditional_escape(self.text)
        if force_text(text) == '':
            text = mark_safe('&nbsp;')
        for wrap in self.wraps:
            text = mark_safe(wrap % text)
        return text 
Example #27
Source File: utils.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def escape_tags(value, valid_tags):
    """ Strips text from the given html string, leaving only tags.
        This functionality requires BeautifulSoup, nothing will be
        done otherwise.
        This isn't perfect. Someone could put javascript in here:
              <a onClick="alert('hi');">test</a>
            So if you use valid_tags, you still need to trust your data entry.
            Or we could try:
              - only escape the non matching bits
              - use BeautifulSoup to understand the elements, escape everything
                else and remove potentially harmful attributes (onClick).
              - Remove this feature entirely. Half-escaping things securely is
                very difficult, developers should not be lured into a false
                sense of security.
    """
    # 1. escape everything
    value = conditional_escape(value)

    # 2. Reenable certain tags
    if valid_tags:
        # TODO: precompile somewhere once?
        tag_re = re.compile(r'&lt;(\s*/?\s*(%s))(.*?\s*)&gt;' %
                            u'|'.join(re.escape(tag) for tag in valid_tags))
        value = tag_re.sub(_replace_quot, value)

    # Allow comments to be hidden
    value = value.replace("&lt;!--", "<!--").replace("--&gt;", "-->")

    return mark_safe(value) 
Example #28
Source File: forms.py    From BikeMaps with MIT License 5 votes vote down vote up
def label_from_instance(self, obj):
        level_indicator = u""

        if getattr(obj, self.parent_field):
            level_indicator = u"--- "

        return mark_safe(level_indicator + conditional_escape(smart_text(getattr(obj, self.label_field)))) 
Example #29
Source File: __init__.py    From django-compat with MIT License 5 votes vote down vote up
def format_html(format_string, *args, **kwargs):
        """
        Similar to str.format, but passes all arguments through conditional_escape,
        and calls 'mark_safe' on the result. This function should be used instead
        of str.format or % interpolation to build up small HTML fragments.
        """
        args_safe = map(html.conditional_escape, args)
        kwargs_safe = dict([(k, html.conditional_escape(v)) for (k, v) in
                            six.iteritems(kwargs)])
        return html.mark_safe(format_string.format(*args_safe, **kwargs_safe)) 
Example #30
Source File: library.py    From bioforum with MIT License 5 votes vote down vote up
def render(self, context):
        resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
        output = self.func(*resolved_args, **resolved_kwargs)
        if self.target_var is not None:
            context[self.target_var] = output
            return ''
        if context.autoescape:
            output = conditional_escape(output)
        return output