用Django开发的页面,之前用的是python3.X,后来又换成python2.X后各种报错,编码问题,于是在所有python文件开头加了编码:#coding=utf-8

但是后来发现,有些文件加了#coding=utf-8还是不起作用,如现在在一个网页报错:

于是在Django项目的views.py下加了如下四行代码:

# coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

后来发现有网友和我的问题一样,但是他的解决方法和我不一样:https://stackoverflow.com/questions/27435622/python-ascii-codec-cant-encode-character-u-xe9-in-position-5-ordinal-not

我也贡献了我的答案my  solution:

Hi,your problem is same with mine,just encode question, you can add bellow code in your views.py of django project:

# coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

my problem:
Error during template rendering
In template D:\PythonProjects\DjangoProject\guest\sign\templates\sign\guest_manage.html, error at line 72

I'm trying to run a quick Django application that pulls data from Google AdWords and exposes the names of accounts that are managed by an agency. When doing so, I get the following error:

UnicodeEncodeError at /account-hierarchy/
'ascii' codec can't encode character u'\xe9' in position 5: ordinal not in range(128)

Here's the snippet:

<table class="pretty-table">
<thead>
<tr>
<td>Customer ID</td>
<td>Client Name</td>
<td>Can Manage Clients</td>
<td>Account Currency</td>
</tr>
</thead>
{% for account in managed_accounts %}
<tr>
{% for field in account %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>

where the call to {{ field }} is the problematic line.

I have already added

<meta http-equiv="content-type" content="text/html; charset=utf-8">

to the template I am rendering, but it still fails, so I believe the problem is not on the HTML template, but rather on the Python/Django engine.

Any ideas how I can fix it?

Here's the View code that renders the template:

def account_hierarchy(request):
manager_ids = settings.MANAGER_IDS
managed_accounts = []
for manager_id in manager_ids:
managed_accounts.extend(adwords_utils.getManagedAccounts(manager_id))
return render_to_response('simple-table.html', {"managed_accounts": managed_accounts})

UPDATED Question

  • Python Version: 2.7.6
  • Models.py is currently empty

What's also curious is that if I remove this:

{% for field in account %}
<td>{{ field }}</td>
{% endfor %}

and I just print out the main array:

{{ managed_accounts }}

it works just fine. Not sure what's going on.

Curious fact #2: As I managed to output the full array, I checked for character 'é' and I didn't find it on the final output. Not sure where it was coming from.

asked Dec 12 '14 at 1:52
daniel_c05

6,951115274
 
    
Perhaps define the __unicode__ method in your models.py would work – dazedconfused Dec 12 '14 at 1:57 
    
Could you also include some related codes in your models.py? – dazedconfused Dec 12 '14 at 2:13
    
I am not using any models yet. So models.py is empty. – daniel_c05 Dec 12 '14 at 2:15
    
Then you would probably need to encode some of the data in managed_accounts – dazedconfused Dec 12 '14 at 2:18

The problem is likely that, in some place in your code, you accidentally defined a data structure to be a Python byte string, when you should have made it a Python Unicode string. This leads Django and Python to convert from Django's Unicode string to your byte string, in a default way, using the ASCII codec.

The error message gives some clues:

  • The error is perhaps occurring when you call account_hierarchy()
  • The phrase character u'\xe9' in position 5: ordinal not in range(128) means that Python is trying to convert Unicode character 'é' (U+00E9) into an ASCII value from 0..127. Look in your data for an 'é'. Which field is it in?
  • The phrase 'ascii' codec means the conversion is likely inadvertent. If you intend to use UTF-8, you wouldn't have called the ASCII codec intentionally. But when you cause a conversion but don't specify a codec, Python uses ASCII.
  • The word encode means conversion from Unicode to byte-oriented encoding. You have read Python's Unicode HOWTO article a couple of times, haven't you?

Function render_to_response() uses settings DEFAULT_CHARSET and DEFAULT_CONTENT_TYPE](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-DEFAULT_CONTENT_TYPE). They should default to 'utf-8' and 'text/html', which should be appropriate for generating a UTF-8 encoded HTML page, but check.

I like the suggestion that you check your models.py to be sure that your models are defined in terms of Unicode data types, not byte string data types. Update: you say models.py is empty, so that won't be much help.

Character handling, and Unicode vs byte strings, are handled differently in Python 2 and Python 3. Which version of Python are you using? Update: Python 2.7.6, thanks. The Unicode HOWTO I linked to above is for Python 2.7.x.

If you make sure your code handles strings as Unicode throughout, unless you really want a byte string, that will likely fix this problem.

Update: Consider modifying your template to give you debugging information. Try something like these expressions, to see what's really in managed_accounts:

</thead>
<tr><td>managed_accounts is: {{ repr(managed_accounts) }}</tr></td>
{% for account in managed_accounts %}
<tr>
{% for field in account %}
<td>{{ type(field) }}, {{ repr(field) }}</td>
{% endfor %}
</tr>
{% endfor %}

[Updated in response to multiple updates from original poster.]

answered Dec 12 '14 at 2:21
Jim DeLaHunt

6,50812948
 
    
Nice and detailed answer! – dazedconfused Dec 12 '14 at 2:29

Your Answer

Django html页面 'ascii' codec can't encode characters in position 8-10: ordinal not的更多相关文章

  1. 解决UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position

    最近用Python写了些爬虫,在爬取一个gb2312的页面时,抛出异常: UnicodeEncodeError: 'ascii' codec can't encode characters in po ...

  2. Python编码问题:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(12

    今天安装了PyScripter编辑器,刚要写代码,突然就出现异常: <span style="font-size:14px;color:#ff0000;">>&g ...

  3. python+selenium运行报错UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

    使用python+selenium运行自动化脚本时,打印某一段文字出现UnicodeEncodeError: 'ascii' codec can't encode characters in posi ...

  4. 'ascii' codec can't encode characters in position 0-8: ordinal not in range(128)的解决办法

    使用的python2.7,运行的时候出现了'ascii' codec can't encode characters in position 0-8: ordinal not in range(128 ...

  5. Pip 安装 出现UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in

    在Python 环境下,使用PiP 命令安装时,报错提示: UnicodeEncodeError: 'ascii' codec can't encode characters in position ...

  6. 解决UnicodeEncodeError: 'ascii' codec can't encode characters in position 问题(转)

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-11: ordinal not in range(128 ...

  7. UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)

    python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报类似这样的错误. UnicodeEncodeError: 'ascii' codec can't ...

  8. 解决Python2.7的UnicodeEncodeError:'ascii' codec can't encode characters in position 0-78: ordinal not in range(128)异常错误

    解决Python2.7的UnicodeEncodeError: 'ascii' codec can't encode异常错误 大家都知道,在使用python进行网络爬虫时,最头疼的就是转码问题,下面是 ...

  9. 【转】Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1

    转自:https://blog.csdn.net/AckClinkz/article/details/78538462 环境 >>> import sys >>> ...

随机推荐

  1. CPU内部组成及原理

    CPU,Central Processing Unit,翻译过来叫中央处理器.是一块超大规模的集成电路,是一台计算机的运算核心(Core)和控制核心( Control Unit).电脑中所有操作都由C ...

  2. java同学毕业后学习之路建议

    第一部分:对于尚未做过Java工作的同学,包括一些在校生以及刚准备转行Java的同学. 滤过: 第二部分:对于参加工作一年以内的同学. 恭喜你,这个时候,你已经拥有了一份Java的工作.这个阶段是你成 ...

  3. namespace的作用及用法

    namespace 所谓namespace,是指标识符的可见范围.C++标准库中的所有标识符都被定义在一个名为 std 的namespace 中. 一.<iostream>和<ios ...

  4. 10.多shard场景下relevence score可能不准确

    主要知识点 多shard场景下relevence score可能不准确的原因 多shard场景下relevence score可能不准确解决方式     一.多shard场景下relevance sc ...

  5. gitblit 搭建本地git服务器

    本文主要描述gitblit搭建本地服务器

  6. Spring 源代码学习(一)

    一 .Spring容器最基本的功能 1. 读取配置文件 2. 校验配置文件的正确性 3. 将配置文件信息加载到内存 4. 通过反射实例化bean对象 5. 构建系统  二 .核心类关系图 图1-1 D ...

  7. elasticsearch match和match_phrase匹配原则(十)

    分词测试 分词后倒排索引结果:可以通过http://127.0.0.1:9200/_analyze 测试 { "analyzer":"ik_max_word", ...

  8. 剖析Spark-Shell

    打开spark-shell,我们可以看到 function main() { if $cygwin; then stty -icanon min 1 -echo > /dev/null 2> ...

  9. hdu 3657最大点权独立集变形(方格取数变形)

    /* 分奇偶为二部图,s与奇建图,t与偶建图,权值为当前数的值,如果遇到必取的权值置为inf. 奇偶建边为相邻的权值为2*(x&y):所有数的值-最小点全覆盖. 置为inf意为不能割掉.奇偶边 ...

  10. 洛谷——P2871 [USACO07DEC]手链Charm Bracelet

    https://www.luogu.org/problem/show?pid=2871 题目描述 Bessie has gone to the mall's jewelry store and spi ...