在Django中声明DB字段时,在verbose_name参数中使用非ascii字符串

Ale*_*lex 2 python django unicode

我宣布:

#This file is using encoding:utf-8
...
class Buddy(models.Model):
    name=models.CharField('???',max_length=200)
    ...
Run Code Online (Sandbox Code Playgroud)

...在models.py中.manage.py syncdb运行顺畅.然而,当我去管理界面并尝试添加一个新的Buddy时,我抓住了一个DjangoUnicodeDecodeError,它说:"'utf8'编解码器无法解码位置0-1中的字节:无效数据.你传入'\ xd4\xc8\xce'(<type'str'<r;)".

我正在使用sqlite3,因此所有字符串都存储为utf8编码的字节串.Django的编码也是utf8.看到django关于这个话题的文档,不知道.

UPD:最终我弄清楚问题是什么.结果是我用ANSI编码保存了我的源代码.

解决方案:我用UTF-8保存了源代码,它创造了奇迹.

Dan*_*aab 5

首先,我将显式定义为Unicode字符串:

class Buddy(models.Model):
    name=models.CharField(u'???',max_len)
Run Code Online (Sandbox Code Playgroud)

注意'u' u'???'.

其次,您是否__unicode__()在模型上定义了功能?如果是这样,请确保它返回Unicode字符串.当Admin界面尝试访问模型的unicode表示时,很可能会出现此错误,而不是在将其添加到数据库时.如果您从中返回非unicode字符串__unicode__(),则可能会导致此问题.