Django:如何确保通过表单发送的输入的正确编码

时间:2013-12-17 15:12:41

标签: python django unicode

我在使用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()的{​​{1}}失败。

回溯看起来像:

send_email

我可能错过了什么?

2 个答案:

答案 0 :(得分:6)

我认为这里的问题是调用str(self.cleaned_data[i[0]]),它会从unicode值中创建一个字节串。例如,u"%s" % str(u"überwach!")将失败,其中u"%s" % unicode(u"überwach!")将正常工作(即使unicode调用在这种情况下是多余的......)

修改:添加一些详细信息:str(u"überwach!")失败并显示UnicodeEncodeError,因为在引擎盖下,它调用u"überwach!".encode("ascii"),但ASCII无法处理变音符号......

可悲的是,我找不到文档中描述的这个问题(str()调用__str__unicode对象,但这个__str__是如何实现的?),但有关该主题的更多信息,请参阅Python Unicode Howto

答案 1 :(得分:3)

您要插入的字符串不是unicode

试试这个:

values.append(u"%s: \t%s" % (unicode(self[i[0]].label), unicode(self.cleaned_data[i[0]]) ) )