【发布时间】:2014-01-05 10:14:11
【问题描述】:
我在使用 Django 的表单上遇到了 Unicode 输入问题:
UnicodeEncodeError at /
'ascii' codec can't encode character u'\xe4' in position 7: ordinal not in range(128)
这发生在 gunicorn 以及在调试模式下运行 Django。我的 form.py 启用了 unicode:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from django import forms
from django.core.mail import send_mail
from django.core.mail import EmailMessage
import datetime
class RTForm(forms.Form):
# ...
institution_station = forms.CharField(max_length=75, label=u"Institute/Station*")
# ...
视图是基于该视图创建的,旨在从输入中构建电子邮件:
class RTview(FormView):
template_name = 'rt-form.html'
form_class = RTForm
success_url = '/thanks/'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
form.send_email()
return super(RTview, self).form_valid(form)
函数 send_email 如下所示:
def send_email(self):
email = EmailMessage(
subject='New item',
#body='Here is the message.',
from_email=self.cleaned_data['email'],
to=['foo@example.com'])
# The dict fields of the form contains all defined fields incl.
# their labels etc. So taking this we can match and check for the
# validated data to fullfill our task.
values = []
for i in self.fields.iteritems():
values.append(u"%s: \t%s" % (self[i[0]].label, str(self.cleaned_data[i[0]]) ) )
email.body = "\n".join(values)
email.send()
将 unicode 放入 institution_station 时,应用程序会响应上述错误,在 values.append() in send_email 处失败。
回溯看起来像:
Internal Server Error: /
Traceback (most recent call last):
File "/home/frlan/.virtualenvs/gascylinders/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/frlan/.virtualenvs/gascylinders/local/lib/python2.7/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/frlan/.virtualenvs/gascylinders/local/lib/python2.7/site-packages/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/home/frlan/.virtualenvs/gascylinders/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 171, in post
return self.form_valid(form)
File "/home/frlan/quellen/git/gascylinders-rt-frontend/gascylinders/rtfrontend/views.py", line 12, in form_valid
form.send_email()
File "/home/frlan/quellen/git/gascylinders-rt-frontend/gascylinders/rtfrontend/forms.py", line 124, in send_email
values.append(u"%s: \t%s" % (self[i[0]].label, str(self.cleaned_data[i[0]]) ) )
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 7: ordinal not in range(128)
我可能错过了什么?
【问题讨论】:
-
刚刚添加了回溯。发生例如插入德语变音符号时。