Str to Ascii Conversion
After attending some python tests I stumbled upon a different DecodeError. The situation is simple: instantiate a string with special characters and try to decode it. Tring to use the Unicode to Ascii method failed.
- def test_title_unicode(self):
- from django.utils.encoding import force_unicode
- title = 'è something!'
- title = force_unicode(title)
- title = title.encode('ascii', 'xmlcharrefreplace')
- error
The difference between the Unicode to Ascii and the current iteration was revealed by printing the variable type:
- def test_title_unicode(self):
- from django.utils.encoding import force_unicode
- title = 'è something'
- print type(title)
- #title = force_unicode(title)
- #title = title.encode('ascii', 'xmlcharrefreplace')
In order to decode a str variable we use a different method:
- def test_title_unicode(self):
- title = 'è something'
- print title
- print type(title)
- title2 = title.decode('latin-1')
- print title2
- print type(title2)
- title3 = unicode(title2)
- print title3
- print type(title3)
- title = title3.encode('ascii', 'xmlcharrefreplace')
- print title
So make sure you check the type and choose the right aproach to convert.
PS: Remember that form.cleaned_data['var'] returns a unicode.



Leave a Comment :