<p>您的<code>user</code>查找返回的是编码的bytestring,而不是Unicode对象。在</p>
<p>当Python2.x被要求连接Unicode和bytestrings编码时,它通过使用默认编码将bytestring解码为Unicode来实现的,默认编码是<code>ascii</code>,除非您进行一些更改。<code># -*- coding: utf-8 -*-</code>指令设置源代码的编码,而不是系统默认编码。在</p>
<p>从测试<code>format</code>来看,它似乎试图转换参数以匹配左侧的类型。在</p>
<p>在2.x下,只要您使用的bytestring可以使用<code>ascii</code>解码,一切都将正常工作:</p>
<pre><code>>>> u'test\u270c {0}'.format('bar')
u'test\u270c bar'
</code></pre>
<p>当然,您正在另一个Unicode对象中格式化:</p>
^{pr2}$
<p>如果在格式化之前省略<code>u</code>,则会得到一个<code>UnicodeEncodeError</code>:</p>
<pre><code>>>> 'foo {0}'.format(u'test\u270c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u270c' in position 4: ordinal not in range(128)
</code></pre>
<p>相反,如果将非ascii字节的编码字符串格式化为Unicode对象,则会得到一个<code>UnicodeDecodeError</code>:</p>
<pre><code>>>> u'foo {0}'.format(test.encode('utf-8'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4: ordinal not in range(128)
</code></pre>
<p>我首先检查<code>get_absolute_url</code>实现。有效的url永远不能包含未转义的非ascii字符,因此它们应该始终可以被ascii解码,但是如果您使用的是标准Django模型<code>first_name</code>和{<cd11>}构建的东西应该是Unicode对象,所以我首先打赌<code>get_absolute_url</code>的错误实现。在</p>