我在 web.py 中有一个表单,由于 string.decode('utf-8') 可以很好地显示,但是当它提交时,我'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)
在 attrget 第 17 行从 web/form.py 得到一个。
该代码如下所示,第 17 行特别是在 except 块中的传递。
def attrget(obj, attr, value=None):
try:
if hasattr(obj, 'has_key') and obj.has_key(attr):
return obj[attr]
except TypeError:
# Handle the case where has_key takes different number of arguments.
# This is the case with Model objects on appengine. See #134
pass
if hasattr(obj, attr):
return getattr(obj, attr)
return value
它一定是关于编码的,因为如果我删除瑞典语 ö 字符,表格就可以工作。这是表单定义。
searchForm = form.Form(
form.Textbox('Startdatum', id='datepickerStart'),
form.Textbox('Slutdatum', id='datepickerEnd'),
form.Textbox('IPadress', validIPaddress),
form.Textbox('Macadress', validMacaddress),
form.Button('Sök'.decode('utf-8'), type='submit', description='Search')
)
第三行调用 Form.validates() 是触发它的地方。
def POST(self):
form = self.searchForm()
if not form.validates():
headerMsg = 'Du skrev något fel, gör om, gör rätt.'.decode('utf-8')
return tpl.index(headerMsg, form)
return tpl.index(headerMsg='Inga rader hittades', form=form)
完整的回溯如下。
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 239, in process
return self.handle()
File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 230, in handle
return self._delegate(fn, self.fvars, args)
File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 420, in _delegate
return handle_class(cls)
File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 396, in handle_class
return tocall(*args)
File "/home/mkbnetadm/netadmin/na.py", line 36, in POST
if not form.validates():
File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/form.py", line 76, in validates
v = attrget(source, i.name)
File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/form.py", line 18, in attrget
if hasattr(obj, attr):
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)
那么在 web.py 中创建表单时我该怎么做才能避免这个错误呢?