I'm getting a django.utils.safestring.SafeText in my unit test:
ipdb> mail.outbox[0].body
u'Dear John Doe,<br>\n<p>\nYou have received a ..
ipdb> type(mail.outbox[0].body)
<class 'django.utils.safestring.SafeText'>
I would like to convert the above into a string, so that I can strip out the \n
characters.. ie I want to use the rstrip()
method.. but I obviously can't do that on a django.utils.safestring.SafeText
object. Ideas?
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.
Create new string based on SafeText
str(mail.outbox[0].body)
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'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With