django.utils.html.conditional_escape

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.

200 Examples 7

Example 1

Project: talk.org
Source File: widgets.py
View license
    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))))

Example 2

Project: talk.org
Source File: widgets.py
View license
    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))

Example 3

View license
    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)

Example 4

Project: GAE-Bulk-Mailer
Source File: forms.py
View license
    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)

Example 5

Project: GAE-Bulk-Mailer
Source File: defaultfilters.py
View license
@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)

Example 6

Project: pretix
Source File: __init__.py
View license
    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),
        }

Example 7

Project: PyClassLessons
Source File: helpers.py
View license
    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)

Example 8

Project: PyClassLessons
Source File: defaultfilters.py
View license
@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)

Example 9

Project: pycontw2016
Source File: utils.py
View license
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))

Example 10

Project: pythondigest
Source File: forms.py
View license
    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)
            }))

Example 11

Project: Misago
Source File: forms.py
View license
    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 ''

Example 12

Project: django-uturn
Source File: uturn.py
View license
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 ''

Example 13

Project: Django--an-app-at-a-time
Source File: helpers.py
View license
    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)

Example 14

Project: Django--an-app-at-a-time
Source File: dummy.py
View license
    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)

Example 15

Project: snowy
Source File: __init__.py
View license
    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))

Example 16

Project: django-adminactions
Source File: massupdate.py
View license
    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)))

Example 17

Project: coursys
Source File: views.py
View license
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)

Example 18

Project: shuup
Source File: toolbar.py
View license
    def render_label(self):
        bits = []
        if self.icon:
            bits.append('<i class="%s"></i>&nbsp;' % self.icon)
        bits.append(conditional_escape(self.text))
        return "".join(force_text(bit) for bit in bits)

Example 19

Project: shuup
Source File: writer.py
View license
    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

Example 20

Project: oioioi
Source File: __init__.py
View license
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))))

Example 21

Project: oioioi
Source File: admin.py
View license
    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)

Example 22

Project: django-easymode
Source File: widgets.py
View license
    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)

Example 23

Project: splunk-webframework
Source File: helpers.py
View license
    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)

Example 24

Project: splunk-webframework
Source File: forms.py
View license
    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)

Example 25

View license
@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)

Example 26

Project: xadmin
Source File: detail.py
View license
    @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

Example 27

Project: xadmin
Source File: list.py
View license
    @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('&nbsp;')
        for wrap in self.wraps:
            text = mark_safe(wrap % text)
        return text

Example 28

Project: xadmin
Source File: widgets.py
View license
    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))

Example 29

Project: django-cropduster
Source File: forms.py
View license
    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]))

Example 30

Project: wateronmars
Source File: html_sanitizers.py
View license
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

Example 31

Project: django-pagedown
Source File: widgets.py
View license
    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)

Example 32

Project: wagtail
Source File: wagtailadmin_tags.py
View license
@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))

Example 33

Project: transifex
Source File: widgets.py
View license
    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)))

Example 34

Project: tri.table
Source File: __init__.py
View license
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)

Example 35

Project: cgstudiomap
Source File: base.py
View license
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

Example 36

Project: cgstudiomap
Source File: defaultfilters.py
View license
@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)

Example 37

Project: dj-dynamic-forms
Source File: admin.py
View license
    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))
        ))

Example 38

Project: dj-dynamic-forms
Source File: admin.py
View license
    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>')

Example 39

Project: dj-dynamic-forms
Source File: test_admin.py
View license
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()
        )
    )

Example 40

Project: django-nonrel
Source File: widgets.py
View license
    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)))

Example 41

Project: django-nonrel
Source File: widgets.py
View license
    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))

Example 42

Project: hue
Source File: helpers.py
View license
    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)

Example 43

Project: hue
Source File: defaultfilters.py
View license
@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)

Example 44

Project: django-wysihtml5
Source File: widgets.py
View license
    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)

Example 45

Project: decode-Django
Source File: helpers.py
View license
    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)

Example 46

Project: decode-Django
Source File: forms.py
View license
    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)

Example 47

View license
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)

Example 48

Project: django
Source File: widgets.py
View license
    def get_template_substitution_values(self, value):
        """
        Return value-related substitutions.
        """
        return {
            'initial': conditional_escape(value),
            'initial_url': conditional_escape(value.url),
        }

Example 49

Project: django
Source File: dummy.py
View license
    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)

Example 50

Project: django
Source File: base.py
View license
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