Python django.utils.safestring.SafeText() Examples

The following are 30 code examples for showing how to use django.utils.safestring.SafeText(). 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: coursys   Author: sfu-fas   File: tests.py    License: 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 2
Project: GTDWeb   Author: lanbing510   File: base.py    License: 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 3
Project: bioforum   Author: reBiocoder   File: html.py    License: 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 4
Project: lexpredict-contraxsuite   Author: LexPredict   File: widgets.py    License: 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 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: html.py    License: 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 6
Project: wagtail   Author: wagtail   File: test_blocks.py    License: 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 7
Project: wagtail   Author: wagtail   File: test_blocks.py    License: 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 8
Project: python   Author: Yeah-Kun   File: base.py    License: 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 9
Project: site   Author: python-discord   File: wiki_extra.py    License: 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 10
Project: luscan-devel   Author: blackye   File: base.py    License: 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 11
Project: openhgsenti   Author: drexly   File: base.py    License: 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 12
Project: python2017   Author: bpgc-cte   File: base.py    License: 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 13
Project: djongo   Author: nesdis   File: tests.py    License: 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 14
Project: coursys   Author: sfu-fas   File: models.py    License: 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 15
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def honour_code_html(self) -> SafeText:
        return markup_to_html(self.honour_code_text, markuplang=self.honour_code_markup, math=self.honour_code_math) 
Example 16
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_html(self) -> SafeText:
        """
        Markup for the question itself
        """
        helper = self.helper()
        return helper.question_html() 
Example 17
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_preview_html(self) -> SafeText:
        """
        Markup for an instructor's preview of the question (e.g. question + MC options)
        """
        helper = self.helper()
        return helper.question_preview_html() 
Example 18
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def entry_head_html(self) -> SafeText:
        """
        Markup this version needs inserted into the <head> on the question page.
        """
        helper = self.helper()
        return helper.entry_head_html() 
Example 19
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def review_html(self) -> SafeText:
        text, markup, math = self.review
        return markup_to_html(text, markup, math=math) 
Example 20
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def answer_html(self) -> SafeText:
        helper = self.question_version.helper()
        return helper.to_html(self) 
Example 21
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def escape_break(text: str) -> SafeText:
    """
    Helper to display student-entered text reasonably (and safely).
    """
    return mark_safe(linebreaks(escape(text))) 
Example 22
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_html(self) -> SafeText:
        text, markup, math = self.version.text
        return markup_to_html(text, markup, math=math) 
Example 23
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_preview_html(self) -> SafeText:
        return self.question_html() 
Example 24
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def entry_head_html(self) -> SafeText:
        return mark_safe('') 
Example 25
Project: coursys   Author: sfu-fas   File: markup.py    License: 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 26
Project: GTDWeb   Author: lanbing510   File: html.py    License: 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 27
Project: GTDWeb   Author: lanbing510   File: base.py    License: 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
Project: django-andablog   Author: WimpyAnalytics   File: test_models.py    License: 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 29
Project: django-andablog   Author: WimpyAnalytics   File: test_models.py    License: 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 30
Project: python   Author: Yeah-Kun   File: html.py    License: 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