简体   繁体   English

为Django表单编码UTF-8

[英]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 但是当

  • I put .encode('utf8') at the end it's solved. 我把.encode('utf8')放在末尾。
  • I use the string without the translation tool 我使用没有翻译工具的字符串
  • I use another text like _('other string') 我使用了另一个文本,例如_('other string')
  • I add string at the end : _('firstname')+'' 我在结尾添加字符串: _('firstname')+''
  • I use the translation in the view : {% 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_lazyugettext_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM