Return Mark_safe String From __str__
I have a class that takes a complex data type and returns the string representation of it using the __str__ method. Then, I can use the object directly in a template. However, I
Solution 1:
You can't; the return value from __str__
must be a str
value.
Template languages that support the __html__
attribute however will automatically call that instead:
classStrTest:def__init__(self, num):
self.num = num
def__str__(self):
return str(self.num)
def__html__(self):
return mark_safe(
'<span style="color: red">Number is {0}</span>'.format(self.num))
Django supports this as of version 1.7, see ticket #7261.
Post a Comment for "Return Mark_safe String From __str__"