django unicode编码/解码错误 [英] django unicode encode/decode errors

查看:135
本文介绍了django unicode编码/解码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站需要能够以不同的语言提供数据。我设置它使用utf-8,并且db设置也被设置为。我在管理员中收到不同的unicode错误。

My site needs to be able to serve data in different languages. I set it so it uses utf-8 and the db settings are set to that as well. I've been getting different different unicode errors over the admin.

例如:


  1. 在管理列表中,列表中的字段包含非ASCII字符时。 (我得到UnicodeDecodeError)

  2. 添加新条目时,如果模型的 unicode 方法返回一个utf-8解码(修复#1),则UnicodeEncodeError 。

  3. 在管理员中使用filter_horizo​​ntal时,如果使用的模型中的数据包含非ASCII字符,则过滤器将从表单中消失。

  1. In the admin list, when a field from the list contains a non ascii char. (i get UnicodeDecodeError)
  2. When adding a new entry, a UnicodeEncodeError if the unicode method for the model returns an utf-8 decode (which fixes #1).
  3. When using a filter_horizontal in the admin, if data from the used model contains non ascii chars, then the filter disappears from the form.

如果我为模型设置 unicode 方法返回,例如:

If I set the unicode method for the model to return for example:

return u'%s' % unicode(self.tag)

这似乎修复了#1和#2,但是当我得到#3。

That seems to fix #1 and #2, but then that's when I get #3.

我一直在寻找一个解决方案,但找不到修复所有不同错误的东西。处理这些的最好方法是什么?

I have been looking a lot for a solution, but can't find something that fixes all different errors. What's the best way to deal with those?

推荐答案

from django.utils.encoding import smart_unicode
...
def __unicode__(self): 
    return smart_unicode(self.tag)

这篇关于django unicode编码/解码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆