当尝试将Django模型转换为XML时,UnicodeEncodeError [英] UnicodeEncodeError when trying to convert Django models to XML
本文介绍了当尝试将Django模型转换为XML时,UnicodeEncodeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现了一个python程序:导出Django数据库到xml文件,将django模型转换为xml表示。尝试运行程序时会收到这些错误。我的模型包含一些用法语编写的文本。
I found a python program: Export Django database to xml file that converts django models to a xml representation. I get these errors when trying to run the program. My models contain some text written in French.
Traceback (most recent call last):
File "xml_export.py", line 71, in <module>
writer.content(value)
File "xml_export.py", line 41, in content
self.output += str(text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3:
ordinal not in range(128)
推荐答案
看起来您的变量 text
包含一个非ASCII字符串。
It looks like your variable text
contains a non-ASCII string.
请参阅:
>>> mystring = u"élève"
>>> mystring
u'\xe9l\xe8ve'
>>> str(mystring)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
所以,您首先需要将您的字符串编码为 UTF-8
:
So, you first need to encode your string into UTF-8
:
>>> str(mystring.encode("utf-8"))
'\xc3\xa9l\xc3\xa8ve'
或者,如果(如评论所示)文本
可能包含除字符串之外的其他变量类型,请使用
Or, if (as the comments show) text
may contain other variable types besides strings, use
self.output += unicode(mystring).encode("utf-8")
这篇关于当尝试将Django模型转换为XML时,UnicodeEncodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文