2

I have a model, "Event", with the following attribute:

desc = models.TextField(blank=True, null=True)

When an instance of the model is saved, it seems to convert special characters to unicode, for example a left double quotation mark becomes "\u201c". Later on, I reference {{ event.desc }} in a template (which works fine), but when I render the template to a string, I get a "UnicodeEncodeError". For context, I am trying to render a simple bit of HTML to a string for posting to an API.

How I render the template:

description = render_to_string('event_description.html', {'event': self})

and the resulting error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 845: ordinal not in range(128)

Is there a way to prevent render_to_string from encoding to ascii, or some more appropriate way to prevent this error?

4

3 回答 3

3

听起来好像有一个.encode()地方试图将其编码u'\u201c'为 ascii 并失败了。
您可以检查回溯以找到该行并将其更改为显式.encode('utf8')
或者将 Python 系统的默认编码更改为 'utf-8': ref here & here

于 2013-04-17T16:20:01.057 回答
0

尝试在您的视图中使用:

# -*- coding: utf-8 -*-

问候,

于 2013-04-17T17:39:29.710 回答
0

同样的问题也发生在我身上;我收到了这个错误:

'ascii' codec can't encode character u'\xf5' in position 14: ordinal not in range(128)
(...)
Error during template rendering
(...)
<h1 id="site-name">{{ servidor }}</h1>

在我的情况下,可能与您的情况相同或可能不同(关于问题的详细信息不足以确定这一点),“servidor”是一个对象吗?Django 试图将其隐式转换为字符串,但使用了错误的编码;这是通过为名为“nome_servidor”的上下文创建一个新参数并事先显式编码来解决的:

context = {
    'nome_servidor': unicode(servidor),
    'servidor': servidor,
    'logs' : servidor.lista_logs()  
}

然后更改模板以显式使用编码字符串:

<h1 id="site-name">{{ nome_servidor }}</h1>
于 2016-02-01T16:37:29.860 回答