Python django.utils.safestring.SafeData() Examples

The following are 30 code examples for showing how to use django.utils.safestring.SafeData(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.safestring , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: debug.py    License: GNU General Public License v2.0 6 votes vote down vote up
def render(self, context):
        try:
            output = self.filter_expression.resolve(context)
            output = template_localtime(output, use_tz=context.use_tz)
            output = localize(output, use_l10n=context.use_l10n)
            output = force_text(output)
        except UnicodeDecodeError:
            return ''
        except Exception as e:
            if not hasattr(e, 'django_template_source'):
                e.django_template_source = self.source
            raise
        if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData):
            return conditional_escape(output)
        else:
            return output 
Example 2
Project: bioforum   Author: reBiocoder   File: i18n.py    License: MIT License 6 votes vote down vote up
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 = mark_safe(value) if is_safe else value
        if self.asvar:
            context[self.asvar] = value
            return ''
        else:
            return value 
Example 3
Project: bioforum   Author: reBiocoder   File: trans_real.py    License: MIT License 6 votes vote down vote up
def gettext(message):
    """
    Translate the 'message' string. It uses the current thread to find the
    translation object to use. If no current translation is activated, the
    message will be run through the default translation object.
    """
    global _default

    eol_message = message.replace('\r\n', '\n').replace('\r', '\n')

    if len(eol_message) == 0:
        # Return an empty value of the corresponding type if an empty message
        # is given, instead of metadata, which is the default gettext behavior.
        result = type(message)("")
    else:
        _default = _default or translation(settings.LANGUAGE_CODE)
        translation_object = getattr(_active, "value", _default)

        result = translation_object.gettext(eol_message)

    if isinstance(message, SafeData):
        return mark_safe(result)

    return result 
Example 4
Project: bioforum   Author: reBiocoder   File: defaultfilters.py    License: MIT License 6 votes vote down vote up
def stringfilter(func):
    """
    Decorator for filters which should only receive strings. The object
    passed as the first positional argument will be converted to a string.
    """
    def _dec(*args, **kwargs):
        if args:
            args = list(args)
            args[0] = str(args[0])
            if (isinstance(args[0], SafeData) and
                    getattr(_dec._decorated_function, 'is_safe', False)):
                return mark_safe(func(*args, **kwargs))
        return func(*args, **kwargs)

    # Include a reference to the real function (used to check original
    # arguments by the template parser, and to bear the 'is_safe' attribute
    # when multiple decorators are applied).
    _dec._decorated_function = getattr(func, '_decorated_function', func)

    return wraps(func)(_dec)


###################
# STRINGS         #
################### 
Example 5
def do_translate(message, translation_function):
        """Copied from django.utils.translation.trans_real"""
        # str() is allowing a bytestring message to remain bytestring on Python 2
        eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))

        if len(eol_message) == 0:
            # Returns an empty value of the corresponding type if an empty message
            # is given, instead of metadata, which is the default gettext behavior.
            result = ''
        else:
            translation_object = translation(get_language())
            result = getattr(translation_object, translation_function)(eol_message)
            if not isinstance(result, six.text_type):
                result = result.decode('utf-8')

        if isinstance(message, SafeData):
            return mark_safe(result)

        return result 
Example 6
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: i18n.py    License: MIT License 6 votes vote down vote up
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 = mark_safe(value) if is_safe else value
        if self.asvar:
            context[self.asvar] = value
            return ''
        else:
            return value 
Example 7
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: trans_real.py    License: MIT License 6 votes vote down vote up
def gettext(message):
    """
    Translate the 'message' string. It uses the current thread to find the
    translation object to use. If no current translation is activated, the
    message will be run through the default translation object.
    """
    global _default

    eol_message = message.replace('\r\n', '\n').replace('\r', '\n')

    if eol_message:
        _default = _default or translation(settings.LANGUAGE_CODE)
        translation_object = getattr(_active, "value", _default)

        result = translation_object.gettext(eol_message)
    else:
        # Return an empty value of the corresponding type if an empty message
        # is given, instead of metadata, which is the default gettext behavior.
        result = type(message)('')

    if isinstance(message, SafeData):
        return mark_safe(result)

    return result 
Example 8
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: defaultfilters.py    License: MIT License 6 votes vote down vote up
def stringfilter(func):
    """
    Decorator for filters which should only receive strings. The object
    passed as the first positional argument will be converted to a string.
    """
    def _dec(*args, **kwargs):
        args = list(args)
        args[0] = str(args[0])
        if (isinstance(args[0], SafeData) and
                getattr(_dec._decorated_function, 'is_safe', False)):
            return mark_safe(func(*args, **kwargs))
        return func(*args, **kwargs)

    # Include a reference to the real function (used to check original
    # arguments by the template parser, and to bear the 'is_safe' attribute
    # when multiple decorators are applied).
    _dec._decorated_function = getattr(func, '_decorated_function', func)

    return wraps(func)(_dec)


###################
# STRINGS         #
################### 
Example 9
Project: python   Author: Yeah-Kun   File: i18n.py    License: Apache License 2.0 6 votes vote down vote up
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 = mark_safe(value) if is_safe else value
        if self.asvar:
            context[self.asvar] = value
            return ''
        else:
            return value 
Example 10
Project: luscan-devel   Author: blackye   File: trans_real.py    License: GNU General Public License v2.0 6 votes vote down vote up
def do_translate(message, translation_function):
    """
    Translates 'message' using the given 'translation_function' name -- which
    will be either gettext or ugettext. It uses the current thread to find the
    translation object to use. If no current translation is activated, the
    message will be run through the default translation object.
    """
    global _default

    # str() is allowing a bytestring message to remain bytestring on Python 2
    eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))
    t = getattr(_active, "value", None)
    if t is not None:
        result = getattr(t, translation_function)(eol_message)
    else:
        if _default is None:
            from django.conf import settings
            _default = translation(settings.LANGUAGE_CODE)
        result = getattr(_default, translation_function)(eol_message)
    if isinstance(message, SafeData):
        return mark_safe(result)
    return result 
Example 11
Project: luscan-devel   Author: blackye   File: debug.py    License: GNU General Public License v2.0 6 votes vote down vote up
def render(self, context):
        try:
            output = self.filter_expression.resolve(context)
            output = template_localtime(output, use_tz=context.use_tz)
            output = localize(output, use_l10n=context.use_l10n)
            output = force_text(output)
        except UnicodeDecodeError:
            return ''
        except Exception as e:
            if not hasattr(e, 'django_template_source'):
                e.django_template_source = self.source
            raise
        if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData):
            return escape(output)
        else:
            return output 
Example 12
Project: openhgsenti   Author: drexly   File: i18n.py    License: Apache License 2.0 6 votes vote down vote up
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 = mark_safe(value) if is_safe else value
        if self.asvar:
            context[self.asvar] = value
            return ''
        else:
            return value 
Example 13
Project: python2017   Author: bpgc-cte   File: i18n.py    License: MIT License 6 votes vote down vote up
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 = mark_safe(value) if is_safe else value
        if self.asvar:
            context[self.asvar] = value
            return ''
        else:
            return value 
Example 14
Project: GTDWeb   Author: lanbing510   File: html.py    License: GNU General Public License v2.0 5 votes vote down vote up
def conditional_escape(text):
    """
    Similar to escape(), except that it doesn't operate on pre-escaped strings.

    This function relies on the __html__ convention used both by Django's
    SafeData class and by third-party libraries like markupsafe.
    """
    if hasattr(text, '__html__'):
        return text.__html__()
    else:
        return escape(text) 
Example 15
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def do_translate(message, translation_function):
    """
    Translates 'message' using the given 'translation_function' name -- which
    will be either gettext or ugettext. It uses the current thread to find the
    translation object to use. If no current translation is activated, the
    message will be run through the default translation object.
    """
    global _default

    # str() is allowing a bytestring message to remain bytestring on Python 2
    eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))

    if len(eol_message) == 0:
        # Returns an empty value of the corresponding type if an empty message
        # is given, instead of metadata, which is the default gettext behavior.
        result = type(message)("")
    else:
        _default = _default or translation(settings.LANGUAGE_CODE)
        translation_object = getattr(_active, "value", _default)

        result = getattr(translation_object, translation_function)(eol_message)

    if isinstance(message, SafeData):
        return mark_safe(result)

    return result 
Example 16
Project: GTDWeb   Author: lanbing510   File: defaultfilters.py    License: GNU General Public License v2.0 5 votes vote down vote up
def stringfilter(func):
    """
    Decorator for filters which should only receive unicode objects. The object
    passed as the first positional argument will be converted to a unicode
    object.
    """
    def _dec(*args, **kwargs):
        if args:
            args = list(args)
            args[0] = force_text(args[0])
            if (isinstance(args[0], SafeData) and
                    getattr(_dec._decorated_function, 'is_safe', False)):
                return mark_safe(func(*args, **kwargs))
        return func(*args, **kwargs)

    # Include a reference to the real function (used to check original
    # arguments by the template parser, and to bear the 'is_safe' attribute
    # when multiple decorators are applied).
    _dec._decorated_function = getattr(func, '_decorated_function', func)

    return wraps(func)(_dec)


###################
# STRINGS         #
################### 
Example 17
Project: GTDWeb   Author: lanbing510   File: defaultfilters.py    License: GNU General Public License v2.0 5 votes vote down vote up
def linenumbers(value, autoescape=True):
    """Displays text with line numbers."""
    lines = value.split('\n')
    # Find the maximum width of the line count, for use with zero padding
    # string format command
    width = six.text_type(len(six.text_type(len(lines))))
    if not autoescape or isinstance(value, SafeData):
        for i, line in enumerate(lines):
            lines[i] = ("%0" + width + "d. %s") % (i + 1, line)
    else:
        for i, line in enumerate(lines):
            lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line))
    return mark_safe('\n'.join(lines)) 
Example 18
Project: GTDWeb   Author: lanbing510   File: defaultfilters.py    License: GNU General Public License v2.0 5 votes vote down vote up
def linebreaks_filter(value, autoescape=True):
    """
    Replaces line breaks in plain text with appropriate HTML; a single
    newline becomes an HTML line break (``<br />``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    return mark_safe(linebreaks(value, autoescape)) 
Example 19
Project: GTDWeb   Author: lanbing510   File: defaultfilters.py    License: GNU General Public License v2.0 5 votes vote down vote up
def linebreaksbr(value, autoescape=True):
    """
    Converts all newlines in a piece of plain text to HTML line breaks
    (``<br />``).
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    value = normalize_newlines(value)
    if autoescape:
        value = escape(value)
    return mark_safe(value.replace('\n', '<br />')) 
Example 20
Project: GTDWeb   Author: lanbing510   File: cookie.py    License: GNU General Public License v2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, Message):
            # Using 0/1 here instead of False/True to produce more compact json
            is_safedata = 1 if isinstance(obj.message, SafeData) else 0
            message = [self.message_key, is_safedata, obj.level, obj.message]
            if obj.extra_tags:
                message.append(obj.extra_tags)
            return message
        return super(MessageEncoder, self).default(obj) 
Example 21
Project: bioforum   Author: reBiocoder   File: html.py    License: MIT License 5 votes vote down vote up
def conditional_escape(text):
    """
    Similar to escape(), except that it doesn't operate on pre-escaped strings.

    This function relies on the __html__ convention used both by Django's
    SafeData class and by third-party libraries like markupsafe.
    """
    if isinstance(text, Promise):
        text = str(text)
    if hasattr(text, '__html__'):
        return text.__html__()
    else:
        return escape(text) 
Example 22
Project: bioforum   Author: reBiocoder   File: trans_real.py    License: MIT License 5 votes vote down vote up
def pgettext(context, message):
    msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
    result = gettext(msg_with_ctxt)
    if CONTEXT_SEPARATOR in result:
        # Translation not found
        result = message
    elif isinstance(message, SafeData):
        result = mark_safe(result)
    return result 
Example 23
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 5 votes vote down vote up
def resolve(self, context, ignore_failures=False):
        if isinstance(self.var, Variable):
            try:
                obj = self.var.resolve(context)
            except VariableDoesNotExist:
                if ignore_failures:
                    obj = None
                else:
                    string_if_invalid = context.template.engine.string_if_invalid
                    if string_if_invalid:
                        if '%s' in string_if_invalid:
                            return string_if_invalid % self.var
                        else:
                            return string_if_invalid
                    else:
                        obj = string_if_invalid
        else:
            obj = self.var
        for func, args in self.filters:
            arg_vals = []
            for lookup, arg in args:
                if not lookup:
                    arg_vals.append(mark_safe(arg))
                else:
                    arg_vals.append(arg.resolve(context))
            if getattr(func, 'expects_localtime', False):
                obj = template_localtime(obj, context.use_tz)
            if getattr(func, 'needs_autoescape', False):
                new_obj = func(obj, autoescape=context.autoescape, *arg_vals)
            else:
                new_obj = func(obj, *arg_vals)
            if getattr(func, 'is_safe', False) and isinstance(obj, SafeData):
                obj = mark_safe(new_obj)
            else:
                obj = new_obj
        return obj 
Example 24
Project: bioforum   Author: reBiocoder   File: defaultfilters.py    License: MIT License 5 votes vote down vote up
def linenumbers(value, autoescape=True):
    """Display text with line numbers."""
    lines = value.split('\n')
    # Find the maximum width of the line count, for use with zero padding
    # string format command
    width = str(len(str(len(lines))))
    if not autoescape or isinstance(value, SafeData):
        for i, line in enumerate(lines):
            lines[i] = ("%0" + width + "d. %s") % (i + 1, line)
    else:
        for i, line in enumerate(lines):
            lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line))
    return mark_safe('\n'.join(lines)) 
Example 25
Project: bioforum   Author: reBiocoder   File: defaultfilters.py    License: MIT License 5 votes vote down vote up
def cut(value, arg):
    """Remove all values of arg from the given string."""
    safe = isinstance(value, SafeData)
    value = value.replace(arg, '')
    if safe and arg != ';':
        return mark_safe(value)
    return value


###################
# HTML STRINGS    #
################### 
Example 26
Project: bioforum   Author: reBiocoder   File: defaultfilters.py    License: MIT License 5 votes vote down vote up
def linebreaks_filter(value, autoescape=True):
    """
    Replace line breaks in plain text with appropriate HTML; a single
    newline becomes an HTML line break (``<br />``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    return mark_safe(linebreaks(value, autoescape)) 
Example 27
Project: bioforum   Author: reBiocoder   File: defaultfilters.py    License: MIT License 5 votes vote down vote up
def linebreaksbr(value, autoescape=True):
    """
    Convert all newlines in a piece of plain text to HTML line breaks
    (``<br />``).
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    value = normalize_newlines(value)
    if autoescape:
        value = escape(value)
    return mark_safe(value.replace('\n', '<br />')) 
Example 28
Project: pasportaservo   Author: tejoesperanto   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def split(value, by=None):
    """
    A template filter to split objects (commonly, strings) by the given argument. A missing argument will split the
    object by any whitespace; if the object cannot be split, it will be wrapped in a list. Strings marked as "safe"
    by Django will still have their parts correctly marked in the resulting list.
    If the argument is of the form 'separator~number', the resulting chunks will have a maximum length of `number`;
    this means that to use a tilde as separator, it must be doubled: '~~'. The chunking will also un-mark the parts
    as "safe" because it might cut HTML tags into several (not-safe-anymore) pieces; Use only for plain text.
    """
    try:
        length = None
        if by == 'NEWLINE':
            by = '\n'
        if by and isinstance(by, str) and '~' in by:
            by, length = by.rsplit('~', maxsplit=1)
            try:
                length = abs(int(length))
            except ValueError:
                length = None
        parts = value.split(by)
    except (ValueError, TypeError, AttributeError):
        parts = [value]

    if isinstance(value, SafeData):
        parts = [mark_safe(part) for part in parts]
    if length:
        parts = [[part[i:i+length] for i in range(0, len(part), length)] if part else [part] for part in parts]
        return [chunk for part_chunks in parts for chunk in part_chunks]
    else:
        return parts 
Example 29
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: html.py    License: MIT License 5 votes vote down vote up
def conditional_escape(text):
    """
    Similar to escape(), except that it doesn't operate on pre-escaped strings.

    This function relies on the __html__ convention used both by Django's
    SafeData class and by third-party libraries like markupsafe.
    """
    if isinstance(text, Promise):
        text = str(text)
    if hasattr(text, '__html__'):
        return text.__html__()
    else:
        return escape(text) 
Example 30
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: trans_real.py    License: MIT License 5 votes vote down vote up
def pgettext(context, message):
    msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
    result = gettext(msg_with_ctxt)
    if CONTEXT_SEPARATOR in result:
        # Translation not found
        result = message
    elif isinstance(message, SafeData):
        result = mark_safe(result)
    return result