尝试将 Django 模型转换为 XML 时出现 UnicodeEncodeError
我找到了一个python程序:将Django数据库导出到xml文件 将 django 模型转换为 xml 表示。我在尝试运行该程序时收到这些错误。我的模型包含一些用法语编写的文本。
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您的变量
text
包含一个非 ASCII 字符串。请参阅:
因此,您首先需要将字符串编码为
UTF-8
:或者,如果(如注释所示)
text
可能包含除字符串之外的其他变量类型,请使用It looks like your variable
text
contains a non-ASCII string.See:
So, you first need to encode your string into
UTF-8
:Or, if (as the comments show)
text
may contain other variable types besides strings, use说真的,不要使用链接的代码。它太糟糕了,而且似乎是由完全不了解 unicode、字符编码、甚至不了解如何构建 XML 文档的人编写的。字符串连接?真的吗?
只是不要使用它。
Seriously, don't use the linked code. It's terrible, and appears to have been written by someone with absolutely no knowledge of unicode, character encodings, or even how to build up an XML document. String concatentation? Really?
Just don't use it.
您是否尝试过使用内置命令:
您在
u'élève'
中使用 unicode 的方式没问题,所以这应该可以工作(正常...)。Did you tried to use the built-in command :
The way you used unicode in
u'élève'
is ok, so this should work (normalement...).