简体   繁体   English

尝试将Django模型转换为XML时出现UnicodeEncodeError

[英]UnicodeEncodeError when trying to convert Django models to XML

I found a python program: Export Django database to xml file that converts django models to a xml representation. 我找到了一个python程序: 将Django数据库导出为xml文件 ,该文件将Django模型转换为xml表示形式。 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) 

It looks like your variable text contains a non-ASCII string. 看起来您的变量text包含非ASCII字符串。

See: 看到:

>>> 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)

So, you first need to encode your string into UTF-8 : 因此,您首先需要将字符串编码为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 或者,如果(如注释所示) text可能包含除字符串之外的其他变量类型,请使用

self.output += unicode(mystring).encode("utf-8")

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. 这太可怕了,似乎是由完全不了解unicode,字符编码甚至不了解如何建立XML文档的人编写的。 String concatentation? 字符串连接? Really? 真?

Just don't use it. 只是不要使用它。

Did you tried to use the built-in command : 您是否尝试过使用内置命令:

./manage.py dumpdata --format xml

The way you used unicode in u'élève' is ok, so this should work (normalement...). 您在u'élève'使用unicode的方式是可以的,所以应该可以正常工作(规范化...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM