Skip to main content
 首页 » 编程设计

python之为 Django 表单编码 UTF-8

2024年08月25日33小虾米

我有一个联系表

class ContactForm(forms.Form): 
    name = forms.CharField(required=True, max_length=100, label=_('firstname')) 
    mail = forms.EmailField(required=True, max_length=150, label=_('mail')) 
 
def display(request): 
    form = ContactForm(request.POST) 
    if form.is_valid():  
       ... 
    else: 
       form = ContactForm()   
 
    return render_to_response('contact.html', {'contact_form' : form}, context_instance=RequestContext(request)) 

使用 from django.utils.translation import gettext_lazy as _

在我的模板 contact.html

<form action="#" method="post" >{% csrf_token %} 
    {{ contact_form.as_p  }} 
    <input type="submit" value="Send" /> 
</form> 

我有这个错误

'ascii' codec can't encode character u'\xe9' in position 2: ordinal not in range(128)

Unicode error hint

The string that could not be encoded/decoded was: Prénom

问题是 _('firstname'))。但是当

  • 我把.encode('utf8')放在最后就解决了。
  • 我用的是没有翻译工具的字符串
  • 我使用另一个文本,例如 _('other string')
  • 我在末尾添加字符串:_('firstname')+''
  • 我在 View 中使用翻译:{% trans "firstname"%}

但我不想在我的联系表(包含更多属性)的所有属性中执行此操作。

我怎样才能同时为姓名和电子邮件执行此操作?

谢谢

请您参考如下方法:

解决方案 是用 ugettext_lazy 替换 gettext_lazy 因为字符串 Prénom 包含一个特殊的 unicode 字母 é