开发者

Django: UnicodeEncodeError when trying to save non-ascii text

I am trying to save a new record with some unicode text in one of the fields.

Saving the unicode text is successful when using the django admin page, but when using the django shell fails with:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 15开发者_StackOverflow中文版: ordinal not in range(128)

Any ideas what's wrong and how to fix it? Thanks!


Try putting u before the string you are working with.

print "ЙЦУКЕН"; #error!
print u"ЙЦУКЕН"; #success!


these handy django build-in conversion functions often do the trick for me. I use them for generating pdfs with special characters.

utility conversion functions

for saving non-ascii text in your model:

from django.utils.encoding import smart_unicode

mymodel.my_field = smart_unicode(myform.cleaned_data["my_non_ascii_text"])
mymodel.save()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜