[Solved]-How to get string from a django.utils.safestring.SafeText


Create new string based on SafeText



As of Django 2.0.4, str(mail.outbox[0].body) no longer works — it returns the same SafeText object. (See this Django commit for why.)

Instead, you can add an empty string to get a regular string back:

type(mail.outbox[0].body + "") == str

In case it helps anyone else, I ran into this problem because I was trying to pass a SafeText from Django into pathlib.Path, which throws TypeError: can't intern SafeText. Adding an empty string fixes it.


You can do the things you want to do with django.utils.safestring.SafeText object.You can apply almost every method as string on SafeText object. Available methods are

'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'islower', 'isnumeric', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'

But they will return unicode object. Example:-

>>> from django.utils.safestring import SafeText
>>> my_safe_text = SafeText('Dear John Doe,<br>\n<p>\nYou have received a ..  ')
>>> type(my_safe_text)
<class 'django.utils.safestring.SafeText'>
>>> my_replaced_unicode = my_safe_text.replace('\n','')
>>> my_replaced_unicode
u'Dear John Doe,<br><p>You have received a ..  '
>>> type(my_replaced_unicode)
<type 'unicode'>
>>> my_rstriped_unicode = my_safe_text.rstrip()
>>> my_rstriped_unicode
u'Dear John Doe,<br>\n<p>\nYou have received a ..'
>>> type(my_rstriped_unicode)
<type 'unicode'>

Leave a comment