我的视图中有代码,用于返回要在文本框中显示的信息。我的名字有fadas(爱尔兰口音)比导致UnicodeDecodeErrors的字母。我逻辑中的一行如下:
return {
...
'wrap_up_form': WrapUpForm(data={u'message': settings.DEFAULT_WRAP_UP_MESSAGE.format(name=customer.given_name.encode('utf-8'))}),
}
我得到的追溯是这个
ERROR 2014-07-24 14:48:26,540 exception_handlers.py:65] 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)
Traceback (most recent call last):
File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/home/rony/Documents/clone-attempt/personal-shopping/vendor/nacelle/core/dispatcher.py", line 24, in nacelle_dispatcher
response = router.default_dispatcher(request, response)
File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1065, in __call__
return self.handler(request, *args, **kwargs)
File "/home/rony/Documents/clone-attempt/personal-shopping/app/utils/decorators.py", line 43, in _arguments_wrapper
return view_method(request, *args, **kwargs)
File "/home/rony/Documents/clone-attempt/personal-shopping/app/utils/decorators.py", line 89, in _arguments_wrapper
output = render_jinja2_template(template_name, context)
File "/home/rony/Documents/clone-attempt/personal-shopping/vendor/nacelle/core/template/renderers.py", line 19, in render_jinja2_template
return renderer.render_template(template_name, **context)
File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2_extras/jinja2.py", line 158, in render_template
return self.environment.get_template(_filename).render(**context)
File "/home/rony/google_appengine/lib/jinja2-2.6/jinja2/environment.py", line 894, in render
return self.environment.handle_exception(exc_info, True)
File "templates/cms/appointments_form.html", line 2, in top-level template code
{% import 'cms/macros.html' as cms_macros %}
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)
我是否需要在模板中添加某种编码?
答案 0 :(得分:0)
customer.given_name
似乎是一个字节字符串而不是Unicode - 因此在调用encode
时,Python首先需要将其解码为Unicode,然后才能重新编码为UTF- 8。
你应该完全放弃编码调用。
答案 1 :(得分:0)
丹尼尔罗斯曼回答说,我也怀疑customer.given_name
是字节串;尝试encode
导致Python尝试解码它。
另一个问题是DEFAULT_WRAP_UP_MESSAGE
是字节字符串文字。
str.format(unicode)
有同样的问题。
解决方案:
.decode(..)
部分。