Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string from a django.utils.safestring.SafeText

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?

like image 238
abbood Avatar asked Jul 20 '16 06:07

abbood


3 Answers

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.

like image 138
Jack Cushman Avatar answered Nov 13 '22 05:11

Jack Cushman


Create new string based on SafeText

str(mail.outbox[0].body)
like image 43
Sergey Gornostaev Avatar answered Nov 13 '22 06:11

Sergey Gornostaev


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'>
like image 32
Iftekhar Uddin Ahmed Avatar answered Nov 13 '22 07:11

Iftekhar Uddin Ahmed