0%

django中verbose_name使用中文出现decode错误

django中verbose_name使用中文出现decode错误解决方法

models.py代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
# coding: utf-8

class Company(models.Model):
name = models.CharField('公司名称',max_length=50)
name_abbr = models.CharField('公司简称',max_length=10)
addr = models.CharField('公司地址',max_length=50)

def __unicode__(self):
return self.name_abbr

class Meta:
verbose_name = "企业信息"
verbose_name_plural = "企业信息"

当sync db的时候出现(unicode error): 'utf8' cannot decode bytes in position 0-1: illegal encoding错误。反复测试,发现将verbose_name及verbose_name_plural删掉后顺利通过。由此推测是verbose_name中中文编码至错,这里的中文编码不是utf-8。将代码修改如下通过:

1
2
verbose_name = ("企业信息").decode("GB2312")
verbose_name_plural = ("企业信息").decode("GB2312")

说明verbose中中文编码为gb2312。奇怪的是字段定义中的中文是能通过,为何字段定义中中文编码与verbose中不同呢?

问题补充:字段定义中的中文会导致显示admin面板是报错,说明本机输入中文全都是GB2312编码,做如下修改后正常显示。不知其他机器中文默认编码也是GB2312吗?

1
2
3
4
5
6
7
8
9
10
11
class Company(models.Model):
name = models.CharField(smart_str(('名称').decode("GB2312")),max_length=50)
name_abbr = models.CharField(smart_str(('简称').decode("GB2312")),max_length=10)
addr = models.CharField(smart_str(('地址').decode("GB2312")),max_length=50,null=True,blank=True)

def __unicode__(self):
return self.name_abbr

class Meta:
verbose_name = ("企业信息").decode("GB2312")
verbose_name_plural = ("企业信息").decode("GB2312")