Python django.utils.safestring.SafeText() Examples

The following are 30 code examples of django.utils.safestring.SafeText(). 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.safestring , or try the search function .
Example #1
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_safe_status(self):
        """
        Translating a string requiring no auto-escaping with gettext or pgettext
        shouldn't change the "safe" status.
        """
        trans_real._active = local()
        trans_real._translations = {}
        s1 = mark_safe('Password')
        s2 = mark_safe('May')
        with translation.override('de', deactivate=True):
            self.assertIs(type(gettext(s1)), SafeText)
            self.assertIs(type(pgettext('month name', s2)), SafeText)
        self.assertEqual('aPassword', SafeText('a') + s1)
        self.assertEqual('Passworda', s1 + SafeText('a'))
        self.assertEqual('Passworda', s1 + mark_safe('a'))
        self.assertEqual('aPassword', mark_safe('a') + s1)
        self.assertEqual('as', mark_safe('a') + mark_safe('s')) 
Example #2
Source File: base.py    From python with Apache License 2.0 6 votes vote down vote up
def adapt_datetime_warn_on_aware_datetime(value, conv):
    # Remove this function and rely on the default adapter in Django 2.0.
    if settings.USE_TZ and timezone.is_aware(value):
        warnings.warn(
            "The MySQL database adapter received an aware datetime (%s), "
            "probably from cursor.execute(). Update your code to pass a "
            "naive datetime in the database connection's time zone (UTC by "
            "default).", RemovedInDjango20Warning)
        # This doesn't account for the database connection's timezone,
        # which isn't known. (That's why this adapter is deprecated.)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)


# MySQLdb returns TIME columns as timedelta -- they are more like timedelta in
# terms of actual behavior as they are signed and include days -- and Django
# expects time, so we still need to override that. We also need to add special
# handling for SafeText and SafeBytes as MySQLdb's type checking is too tight
# to catch those (see Django ticket #6052). 
Example #3
Source File: base.py    From python2017 with MIT License 6 votes vote down vote up
def adapt_datetime_warn_on_aware_datetime(value, conv):
    # Remove this function and rely on the default adapter in Django 2.0.
    if settings.USE_TZ and timezone.is_aware(value):
        warnings.warn(
            "The MySQL database adapter received an aware datetime (%s), "
            "probably from cursor.execute(). Update your code to pass a "
            "naive datetime in the database connection's time zone (UTC by "
            "default).", RemovedInDjango20Warning)
        # This doesn't account for the database connection's timezone,
        # which isn't known. (That's why this adapter is deprecated.)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)


# MySQLdb returns TIME columns as timedelta -- they are more like timedelta in
# terms of actual behavior as they are signed and include days -- and Django
# expects time, so we still need to override that. We also need to add special
# handling for SafeText and SafeBytes as MySQLdb's type checking is too tight
# to catch those (see Django ticket #6052). 
Example #4
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_custom_render_form_template_jinja(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock(required=False)
            link = blocks.URLBlock(required=False)

            class Meta:
                form_template = 'tests/jinja2/struct_block_form_template.html'

        block = LinkBlock()
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertIn('<div>Hello</div>', html)
        self.assertHTMLEqual('<div>Hello</div>', html)
        self.assertTrue(isinstance(html, SafeText)) 
Example #5
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_custom_render_form_template(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock(required=False)
            link = blocks.URLBlock(required=False)

            class Meta:
                form_template = 'tests/block_forms/struct_block_form_template.html'

        block = LinkBlock()
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertIn('<div>Hello</div>', html)
        self.assertHTMLEqual('<div>Hello</div>', html)
        self.assertTrue(isinstance(html, SafeText)) 
Example #6
Source File: html.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def html_safe(klass):
    """
    A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.
    """
    if '__html__' in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it defines "
            "__html__()." % klass.__name__
        )
    if '__str__' not in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it doesn't "
            "define __str__()." % klass.__name__
        )
    klass_str = klass.__str__
    klass.__str__ = lambda self: mark_safe(klass_str(self))
    klass.__html__ = lambda self: str(self)
    return klass 
Example #7
Source File: base.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def adapt_datetime_warn_on_aware_datetime(value, conv):
    # Remove this function and rely on the default adapter in Django 2.0.
    if settings.USE_TZ and timezone.is_aware(value):
        warnings.warn(
            "The MySQL database adapter received an aware datetime (%s), "
            "probably from cursor.execute(). Update your code to pass a "
            "naive datetime in the database connection's time zone (UTC by "
            "default).", RemovedInDjango20Warning)
        # This doesn't account for the database connection's timezone,
        # which isn't known. (That's why this adapter is deprecated.)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052). 
Example #8
Source File: widgets.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, name: str, value, attrs=None, renderer=None):
        """
        name='project', value=None, attrs={'id': 'id_project'}
        <select name="project" id="id_project">
        """
        wig_id = attrs['id']
        html = self.build_master_change_script(wig_id)
        html += f'<select name="{name}" id="{wig_id}">\n'
        html += '    <option value="" selected>---------</option>\n'

        proj_set = [(p.pk, p.type.code, p.name, p.type_id) for p in self.choices.queryset.order_by('-pk')]

        for id, proj_type, proj_name, proj_type_pk in proj_set:
            val_str = f'{proj_name} ({proj_type}, #{id})'
            html += f'    <option value="{id}" data_type="{proj_type_pk}" >'
            html += f'{val_str}</option>\n'

        html += '</select>\n'
        html_safe = SafeText(html)
        return html_safe 
Example #9
Source File: html.py    From bioforum with MIT License 6 votes vote down vote up
def html_safe(klass):
    """
    A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.
    """
    if '__html__' in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it defines "
            "__html__()." % klass.__name__
        )
    if '__str__' not in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it doesn't "
            "define __str__()." % klass.__name__
        )
    klass_str = klass.__str__
    klass.__str__ = lambda self: mark_safe(klass_str(self))
    klass.__html__ = lambda self: str(self)
    return klass 
Example #10
Source File: tests.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def test_all_markup_langs(self):
        """
        Make sure each markup option returns the same way.
        """
        correct = '<p>Paragraph <strong>1</strong> \u2605\U0001F600</p>'
        markup_samples = [
            ('creole', '''Paragraph **1** \u2605\U0001F600'''),
            ('markdown', '''Paragraph **1** \u2605\U0001F600'''),
            ('html', '''<p>Paragraph <strong>1</strong> \u2605\U0001F600'''),
            ('textile', '''Paragraph *1* \u2605\U0001F600'''),
        ]
        for lang, markup in markup_samples:
            result = markup_to_html(markup, lang)
            self.assertIsInstance(result, SafeText)
            self.assertEqual(result.strip(), correct)

        result = markup_to_html('Paragraph <1> \u2605\U0001F600', 'plain')
        self.assertIsInstance(result, SafeText)
        self.assertEqual(result.strip(), '<p>Paragraph &lt;1&gt; \u2605\U0001F600</p>') 
Example #11
Source File: base.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects. 
Example #12
Source File: wiki_extra.py    From site with MIT License 6 votes vote down vote up
def render_field(field: Field, render_labels: bool = True) -> SafeText:
    """
    Renders a form field using a custom template designed specifically for the wiki forms.

    As the wiki uses custom form rendering logic, we were unable to make use of Crispy Forms for
    it. This means that, in order to customize the form fields, we needed to be able to render
    the fields manually. This function handles that logic.

    Sometimes we don't want to render the label that goes with a field - the `render_labels`
    argument defaults to True, but can be set to False if the label shouldn't be rendered.

    The label rendering logic is left up to the template.

    Usage: `{% render_field field_obj [render_labels=True/False] %}`
    """
    unbound_field = get_unbound_field(field)

    if not isinstance(render_labels, bool):
        render_labels = True

    template_path = TEMPLATES.get(unbound_field.__class__, TEMPLATE_PATH.format("in_place_render"))
    is_markitup = isinstance(unbound_field.widget, MarkItUpWidget)
    context = {"field": field, "is_markitup": is_markitup, "render_labels": render_labels}

    return render(template_path, context) 
Example #13
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects. 
Example #14
Source File: html.py    From python with Apache License 2.0 5 votes vote down vote up
def html_safe(klass):
    """
    A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.
    """
    if '__html__' in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it defines "
            "__html__()." % klass.__name__
        )
    if six.PY2:
        if '__unicode__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __unicode__()." % klass.__name__
            )
        klass_unicode = klass.__unicode__
        klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))
        klass.__html__ = lambda self: unicode(self)  # NOQA: unicode undefined on PY3
    else:
        if '__str__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __str__()." % klass.__name__
            )
        klass_str = klass.__str__
        klass.__str__ = lambda self: mark_safe(klass_str(self))
        klass.__html__ = lambda self: str(self)
    return klass 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_safestr(self):
        c = Company(cents_paid=12, products_delivered=1)
        c.name = SafeText('Iñtërnâtiônàlizætiøn1')
        c.save() 
Example #16
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
        return conn 
Example #17
Source File: wiki_extra.py    From site with MIT License 5 votes vote down vote up
def render(template_path: str, context: Dict[str, Any]) -> SafeText:
    """
    Renders a template at a specified path, with the provided context dictionary.

    This was extracted mostly for the sake of mocking it out in the tests - but do note that
    the resulting rendered template is wrapped with `mark_safe`, so it will not be escaped.
    """
    return mark_safe(get_template(template_path).render(context))  # noqa: S703, S308 
Example #18
Source File: base.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _cursor(self):
        new_connection = False
        if not self._valid_connection():
            new_connection = True
            kwargs = {
                'conv': django_conversions,
                'charset': 'utf8',
            }
            if not six.PY3:
                kwargs['use_unicode'] = True
            settings_dict = self.settings_dict
            if settings_dict['USER']:
                kwargs['user'] = settings_dict['USER']
            if settings_dict['NAME']:
                kwargs['db'] = settings_dict['NAME']
            if settings_dict['PASSWORD']:
                kwargs['passwd'] = force_str(settings_dict['PASSWORD'])
            if settings_dict['HOST'].startswith('/'):
                kwargs['unix_socket'] = settings_dict['HOST']
            elif settings_dict['HOST']:
                kwargs['host'] = settings_dict['HOST']
            if settings_dict['PORT']:
                kwargs['port'] = int(settings_dict['PORT'])
            # We need the number of potentially affected rows after an
            # "UPDATE", not the number of changed rows.
            kwargs['client_flag'] = CLIENT.FOUND_ROWS
            kwargs.update(settings_dict['OPTIONS'])
            self.connection = Database.connect(**kwargs)
            self.connection.encoders[SafeText] = self.connection.encoders[six.text_type]
            self.connection.encoders[SafeBytes] = self.connection.encoders[bytes]
            connection_created.send(sender=self.__class__, connection=self)
        cursor = self.connection.cursor()
        if new_connection:
            # SQL_AUTO_IS_NULL in MySQL controls whether an AUTO_INCREMENT column
            # on a recently-inserted row will return when the field is tested for
            # NULL.  Disabling this value brings this aspect of MySQL in line with
            # SQL standards.
            cursor.execute('SET SQL_AUTO_IS_NULL = 0')
        return CursorWrapper(cursor) 
Example #19
Source File: html.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def html_safe(klass):
    """
    A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.
    """
    if '__html__' in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it defines "
            "__html__()." % klass.__name__
        )
    if six.PY2:
        if '__unicode__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __unicode__()." % klass.__name__
            )
        klass_unicode = klass.__unicode__
        klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))
        klass.__html__ = lambda self: unicode(self)  # NOQA: unicode undefined on PY3
    else:
        if '__str__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __str__()." % klass.__name__
            )
        klass_str = klass.__str__
        klass.__str__ = lambda self: mark_safe(klass_str(self))
        klass.__html__ = lambda self: str(self)
    return klass 
Example #20
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
        return conn 
Example #21
Source File: htk_tags.py    From django-htk with MIT License 5 votes vote down vote up
def btoa(value):
    """Base64 encode
    Binary to ASCII
    """
    if type(value) in (str, SafeText):
        value = value.encode('utf-8')

    # Convert bytes to str for for use in template
    value = base64.b64encode(value).decode('utf-8')
    return value


# Maths 
Example #22
Source File: html.py    From python2017 with MIT License 5 votes vote down vote up
def html_safe(klass):
    """
    A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.
    """
    if '__html__' in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it defines "
            "__html__()." % klass.__name__
        )
    if six.PY2:
        if '__unicode__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __unicode__()." % klass.__name__
            )
        klass_unicode = klass.__unicode__
        klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))
        klass.__html__ = lambda self: unicode(self)  # NOQA: unicode undefined on PY3
    else:
        if '__str__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __str__()." % klass.__name__
            )
        klass_str = klass.__str__
        klass.__str__ = lambda self: mark_safe(klass_str(self))
        klass.__html__ = lambda self: str(self)
    return klass 
Example #23
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
        return conn 
Example #24
Source File: models.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def intro_html(self) -> SafeText:
        return markup_to_html(self.intro, markuplang=self.markup, math=self.math) 
Example #25
Source File: test_models.py    From django-andablog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_duplicate_long_slugs_should_get_a_timestamp(self):
        """If a long title has a shortened slug that is a duplicate, it should have a timestamp"""
        self.entry.title = SafeText("Here's a really long title, for testing slug character restrictions")
        self.entry.save()

        duplicate_entry = models.Entry.objects.create(title=self.entry.title, content=self.entry.content)

        self.assertNotEqual(self.entry.slug, duplicate_entry.slug)
        # This is not ideal, but a portion of the original slug is in the duplicate
        self.assertIn(self.entry.slug[:25], duplicate_entry.slug) 
Example #26
Source File: test_models.py    From django-andablog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_long_slugs_should_not_get_split_midword(self):
        """The slug should not get split mid-word."""
        self.entry.title = SafeText("Please tell me where everyone is getting their assumptions about me?" * 100)
        self.entry.save()
        # The ending should not be a split word.
        self.assertEqual(self.entry.slug[-25:], 'everyone-is-getting-their') 
Example #27
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
        return conn 
Example #28
Source File: html.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def html_safe(klass):
    """
    A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.
    """
    if '__html__' in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it defines "
            "__html__()." % klass.__name__
        )
    if six.PY2:
        if '__unicode__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __unicode__()." % klass.__name__
            )
        klass_unicode = klass.__unicode__
        klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))
        klass.__html__ = lambda self: unicode(self)  # NOQA: unicode undefined on PY3
    else:
        if '__str__' not in klass.__dict__:
            raise ValueError(
                "can't apply @html_safe to %s because it doesn't "
                "define __str__()." % klass.__name__
            )
        klass_str = klass.__str__
        klass.__str__ = lambda self: mark_safe(klass_str(self))
        klass.__html__ = lambda self: str(self)
    return klass 
Example #29
Source File: markup.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def ensure_sanitary_markup(markup, markuplang, restricted=False):
    """
    Double-check that the markup we're about to store is safe.

    :param markup: markup
    :param markuplang: markup language contained in markup argument
    :param restricted: use the restricted HTML subset?
    :return: sanitary markup
    """
    if markuplang == 'html' and not isinstance(markup, SafeText):
        # HTML input, but not a SafeText (which comes from sanitize_html)
        return sanitize_html(markup, restricted=restricted)

    # otherwise, we trust the markup language processor to safe output.
    return markup 
Example #30
Source File: base.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def entry_head_html(self) -> SafeText:
        return mark_safe('')