简体   繁体   English

Django-latin1中的POST数据,解码为utf-8

[英]Django - POST data in latin1, decode as utf-8

Using mysql (not my choice), everything is set to utf8 , utf8_general_ci . 使用mysql(不是我的选择),所有内容都设置为utf8utf8_general_ci In the normal case everything is utf8 and happy. 在正常情况下,一切都是utf8并很高兴。

However, if I POST sth like É's , some latin1 , and save it into the database as normal, I can't call .decode('utf-8') on the resulting model field: 但是,如果我像É's一样.decode('utf-8')一些latin1 ,然后像往常一样将其保存到数据库中,则无法在结果模型字段上调用.decode('utf-8')

>>> myinstance.myfield.decode('utf-8')
...

UnicodeEncodeError: 'ascii' codec can't encode character u'\xc9' in position 7: ordinal not in range(128)

I want to clean all incoming data so that it can be decoded as utf8 . 我想清除所有传入的数据,以便可以将其解码为utf8

Trying an approach like this just causes the UnicodeEncodeError upfront. 尝试的方法像这样只是使UnicodeEncodeError前期。

Edit: As Daniel's answer suggests, this question comes from a misunderstanding. 编辑:正如丹尼尔的答案所暗示的,这个问题来自一个误解。 latin1 is not the culprit here. latin1不是这里的罪魁祸首。 .decode('utf-8') tries to encode to ASCII, so, it will fail for unicode like u'팩맨'.decode('utf-8') . .decode('utf-8')尝试编码为ASCII,因此,对于u'팩맨'.decode('utf-8')这样的unicode它将失败。 It pains me to leave this question up, knowing what I know now. 知道我现在所知道的,让我留下这个问题很痛苦。 But, maybe it will help someone. 但是,也许它将帮助某人。 I think, since the data is actually coming back as unicode, what we were trying to do was actually equivalent to u'É''.decode('utf-8') . 我认为,由于数据实际上是以unicode形式返回的,因此我们试图做的实际上等效于u'É''.decode('utf-8')

Django fields are always unicode. Django字段始终是unicode。 Trying to call decode on them means that Python will try to encode first, to ASCII, before trying to decode as UTF-8. 尝试对其进行调用decode意味着Python将先尝试将其编码为ASCII,然后再尝试将其解码为UTF-8。 That clearly isn't what you want. 那显然不是您想要的。 I expect you actually just want to do myinstance.myfield.encode('utf-8') . 我希望您实际上只是想做myinstance.myfield.encode('utf-8')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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