2

I'm writing a class that will be returned by a custom template filter. It has a __str__ method that returns HTML. I don't want that HTML to be escaped.

I've tried just calling mark_safe on my string before returning it from the __str__ method, but the result is escaped. I'm assuming this is because Django is checking if the object is safe before converting it to a string?

Can I somehow mark the class itself as safe?

e.g.

class ParagraphTag(object):
    def __init__(self, text):
        self.text = text

    def __str__(self):
        return mark_safe('<p>{}</p>'.format(self.text + 'baz'))

@register.filter(name='paragraph_tag')
def paragraph_tag(text):
    return ParagraphTag(text)

Rendering a paragraph tag object in a template then results in it being escaped.

e.g. {{ paragraph_tag }} -> <p>foo</p>

If I call mark_safe on the ParagraphTag object itself when returning it from my template filter, then it gets turned into a SafeBytes object which is not what I want. I want to have the rich object available in my template and only have it converted to a string when rendered.

4
  • 1
    can you not return safe from the template filter? It would help if you could show an example snippet of code.
    – Sayse
    May 17, 2016 at 10:05
  • @Sayse added an example
    – Acorn
    May 17, 2016 at 10:10
  • In your first sentence you say that this class will be returned from a custom template filter, so do you have an example of that? it would make more sense (to me) to use safe in that. Otherwise, what problem are you trying to solve by doing this?
    – Sayse
    May 17, 2016 at 10:48
  • @Sayse as I mentioned, if I try and mark my rich object as safe it gets turned into a SafeBytes object. My goal was to have an object of which I could interrogate individual attributes, for example as part of a haschanged block, but knows how to render itself as HTML.
    – Acorn
    May 17, 2016 at 10:52

2 Answers 2

5

Django generally uses unicode() to get a string out of Python objects. You have to implement __unicode__ so that it returns a safe Unicode string. Otherwie, the default value that will be returned will be taken from __str__ but will be made unsafe by the transformation.

For the record, here is the code I used to diagnose it:

from django.utils.html import mark_safe

class ParagraphTag(object):

    def __init__(self, text):
        self.text = text

    def __str__(self):
        return mark_safe('<p>{}</p>'.format(self.text + 'baz'))

print str(ParagraphTag("foo")).__class__
print str(ParagraphTag("foo"))
print 
print unicode(ParagraphTag("foo")).__class__
print unicode(ParagraphTag("foo"))
print mark_safe(unicode(ParagraphTag("foo"))).__class__

This will output:

<class 'django.utils.safestring.SafeBytes'>
<p>foobaz</p>

<type 'unicode'>
<p>foobaz</p>
<class 'django.utils.safestring.SafeText'>

And here is an example of a class that will produce safe Unicode:

class ParagraphTagFixed(object):

    def __init__(self, text):
        self.text = text

    def __str__(self):
        return unicode(self).encode("utf-8")

    def __unicode__(self):
        return mark_safe(u'<p>{}</p>'.format(self.text + u'baz'))

print unicode(ParagraphTagFixed("foo")).__class__
print unicode(ParagraphTagFixed("foo"))
print str(ParagraphTagFixed("foo")).__class__
print str(ParagraphTagFixed("foo"))

It will show:

<class 'django.utils.safestring.SafeText'>
<p>foobaz</p>
<class 'django.utils.safestring.SafeBytes'>
<p>foobaz</p>
2

I think that __str__ should return a string. Yours does not, and that is what is causing you trouble.

Django rather uses __html__ for escaped strings. In fact it provides an html_safe deecorator that creates this method based on your definition of __str__.

On Python 3, you can define your class like that:

from django.utils.html import html_safe

@html_safe
class Test():
    def __str__(self):
        return '<p>Hey</p>'

And on Python 2:

from django.utils.html import html_safe
from django.utils.encoding import python_2_unicode_compatible

@html_safe
@python_2_unicode_compatible
class Test():
    def __str__(self):
        return '<p>Hey</p>'

(or you can define __unicode__ rather than __str__).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.