[英]Encode UTF-8 for Django form
I have a contact form 我有联系表
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))
With from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_lazy as _
使用from django.utils.translation import gettext_lazy as _
In my template contact.html
在我的模板
contact.html
<form action="#" method="post" >{% csrf_token %}
{{ contact_form.as_p }}
<input type="submit" value="Send" />
</form>
I have this error 我有这个错误
'ascii' codec can't encode character u'\\xe9' in position 2: ordinal not in range(128)
'ascii'编解码器无法在位置2编码字符u'\\ xe9':序数不在范围内(128)
Unicode error hint
Unicode错误提示
The string that could not be encoded/decoded was: Prénom
无法编码/解码的字符串是:Prénom
The problem is _('firstname'))
. 问题是
_('firstname'))
。 But it works when 但是当
.encode('utf8')
at the end it's solved. .encode('utf8')
放在末尾。 _('other string')
_('other string')
_('firstname')+''
_('firstname')+''
{% trans "firstname" %}
{% trans "firstname" %}
But I don't want to do this in all attributs of my contact form (which contains more attributs). 但我不想在联系表格的所有属性中都包含此属性(包含更多属性)。
How can I do that for name and email both ? 我该如何同时填写姓名和电子邮件?
Thanks 谢谢
解决办法是更换gettext_lazy
由ugettext_lazy
因为字符串Prénom
包含一个特殊的Unicode信é
Type on the first line: 在第一行输入:
# -*- coding: utf-8 -*-
Python recognises this line as instructions of encoding type for your entire file. Python将这一行识别为整个文件的编码类型说明。
You don't specify whether you use ModelForms or not, but can you check in your template that your browser will correctly encode the submitted data with the content='text/html; charset=UTF-8'
您无需指定是否使用ModelForms,但可以在模板中检查浏览器是否使用
content='text/html; charset=UTF-8'
正确编码提交的数据content='text/html; charset=UTF-8'
content='text/html; charset=UTF-8'
attribute in the form
tag? content='text/html; charset=UTF-8'
属性在form
标记中? Like: 喜欢:
<form action='/someurl' method='post' content='text/html; charset=UTF-8'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.