Re: [問題] Python 2.7與UTF-8

看板Python作者 (iSuck)時間12年前 (2013/08/16 16:12), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《doomleika (iSuck)》之銘言: : 前陣子寫django東西的時候遇到了一點問題: : 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128) : ... : Unicode error hint : The string that could not be encoded/decoded was: 登入失敗,請修正帳號密碼 : Error during template rendering 圖多,建議使用shift+Q以網頁模式瀏覽較好 實際把東西放回去後發現並沒有解決問題,我弄了一個簡化版的source出來: https://bitbucket.org/doomleika/django_form_override/src forms.py http://0rz.tw/WZmEs 我使用了繼承ErrorList的方式讓錯誤訊息的<ul>可以塞入bootstrap的錯誤class @python_2_unicode_compatible class BootstrapErrorList(ErrorList): def as_ul(self): if not self: return '' return format_html('<ul class="errorlist alert alert-error">{0}</ul>', format_html_join('', '<li>{0}</li>', ((force_text(e),) for e in self) ) ) def __str__(self): return self.as_ul() 然後用一個Form Class使用這個ErrorList class BootstrapForm(forms.Form): def __init__(self, *args, **kwargs): new_kwargs = {'error_class': BootstrapErrorList} new_kwargs.update(kwargs) super(BootstrapForm, self).__init__(*args, **new_kwargs) 然後讓官方推薦的方式做form的clean class FormWithOverride(BootstrapForm): iamalwayswrong = forms.CharField(max_length=200) def clean(self): cleaned_data = super(FormWithOverride, self).clean() raise forms.ValidationError(u'錯') return cleaned_data 作為對照,這邊使用了一個不使用BootstrapForm的標準Form,寫法完全一樣 class FormWithoutOverride(forms.Form): iamalwayswrong = forms.CharField(max_length=200) def clean(self): cleaned_data = super(FormWithoutOverride, self).clean() raise forms.ValidationError(u'錯') return cleaned_data views.py基本上就只是兩個不同版本form的對照 # -*- coding: UTF-8 -*- # Create your views here. from django.shortcuts import render from test_app.forms import * def without_override(request): if request.method == 'GET': form = FormWithoutOverride() if request.method == 'POST': form = FormWithoutOverride(request.POST) if form.is_valid(): # will never be valid pass return render(request, 'normal_form.html', {'form': form}) def with_override(request): if request.method == 'GET': form = FormWithOverride() if request.method == 'POST': form = FormWithOverride(request.POST) if form.is_valid(): # will never be valid pass return render(request, 'override_form.html', {'form': form}) template的實作完全trivial(form.as_p)就不列出來占版面了 線上展示的網頁在此: 沒有override的版本 http://192.241.167.204/normal/ 畫面 http://imgur.com/yDDLxMw
有override的版本 http://192.241.167.204/override/ 畫面 http://imgur.com/3oVRH4D
沒有override輸入錯誤的畫面,正常 http://imgur.com/JKSetfu
override submit後整個就掛掉了... http://imgur.com/T1Vf92Q
請問我的問題是在哪呢?謝謝m(_ _)m

08/17 01:53, , 1F
format_html 裡面的字串加上u (?)
08/17 01:53, 1F
超神奇...老外在stackoverflow回答一樣的答案...就過了o_O http://0rz.tw/1tzAS 不能理解這是怎麼回事? 原本繼承的class ErrorList用的string裡面並沒有使用u'i_am_unicode_string'而是 'regular_string' 但他還是能過,這是什麼原因o_O ※ 編輯: doomleika 來自: 42.76.232.31 (08/17 02:13)
文章代碼(AID): #1I3azVUa (Python)
討論串 (同標題文章)
文章代碼(AID): #1I3azVUa (Python)