我对 unicode 的性质有点熟悉,但我不确定所有部分是如何组合在一起的。在管理页面中显示特定实例时出错。
Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode character u'\u2019' in position 29: ordinal not in range(128)
这是我的模型:
class Proposal(models.Model):
project = models.ForeignKey(Project)
dateCreated = models.DateTimeField(editable=False)
xml = models.TextField(max_length=1000000)
def __str__(self):
return str('Proposal for: %s' % self.project.name)
我已经进入我的 mysql 数据库并验证 DB、表和列都整理为 utf8_unicode_ci,所以我不明白为什么页面试图呈现为 ascii。查看各种论坛和文档,我看到提到 str 和 unicode 功能,但它们似乎与此无关,因为实例列表在管理页面上显示得很好。它只是显示导致问题的实际实例形式。
这是我从 phpmyadmin 中提取的一些示例 xml ...
<?xml version="1.0" encoding="UTF-8"?>
<proposal>
<section title="OVERVIEW">
<section title="Introduction">
<text>
This proposal is not in the system because it was completed as an agreement in Word previous to us getting this application up and running. Please refer to the attachments in this project for documentation or to see the agreement.
</text>
</section>
</section>
</proposal>
我什至试图故意排除 xml(从长远来看我不能这样做,因为我希望它在管理部分可编辑),但我仍然遇到同样的错误,所以我什至没有确信 xml 甚至是问题所在。如果 xml 不是问题,我不知道还有什么可以阻止显示此页面。
class ProposalAdmin(admin.ModelAdmin):
exclude = ('xml',)
admin.site.register(Project)
最佳答案
有一个 ’
某个地方的字符,可能在 self.project.name
.如果您检查整个错误消息,您可能会找到它。
但是,如果您从数据库中获取 unicode 结果,那么执行以下操作可能会更明智:
def __str__(self):
return ('Proposal for: %s' % self.project.name).encode('ascii', errors='replace')
最聪明的做法,因为它是 recommended by the Django documentation ,是为了实现
__unicode__
函数代替:def __unicode__(self):
return u'Proposal for: %s' % self.project.name
关于管理页面上的 django unicode 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6560226/