【发布时间】:2015-06-17 19:07:30
【问题描述】:
这是我在 django 中处理的另一个 UnicodeDecodeError。我找不到解决方法。
我正在尝试创建一个对象:
nivel_obj = Nivel.objects.filter(id=nivel_id)
nueva_matricula = Matricula(nivel=nivel_obj, ano_lectivo=ano_lectivo, alumno=a)
nueva_matricula.save()
“Matricula”对象有一个“nivel_obj”,它是一个外键。 “nivel_obj”的名称是一个无法编码/解码的字符串。
我该如何解决这个问题?
这些是模型:
class Nivel(models.Model):
"""
Ej - "Octavo de Basica, 6to Curso"
"""
nombre = models.CharField(max_length=150)
class Meta:
verbose_name_plural = "niveles"
def __unicode__(self):
return u"%s" % (self.nombre)
class Matricula(models.Model):
ano_lectivo = models.PositiveIntegerField(validators=[MaxValueValidator(9999)])
alumno = models.ForeignKey(Alumno)
nivel = models.ForeignKey(Nivel, null=True) <----
status = models.CharField(max_length=150, choices=(("A", "Activo"), ("I", "Inactivo")))
def validate_unique(self, exclude=None):
if Matricula.objects.filter(alumno=self.alumno, nivel=self.nivel, ano_lectivo=self.ano_lectivo).exists():
error = u'Ya existe una matrícula igual, por favor revisa el año, el nivel y el alumno'
raise ValidationError({NON_FIELD_ERRORS: error})
else:
pass
class Meta:
verbose_name_plural = "matrículas"
verbose_name = "matrícula"
ordering = ("alumno",)
def __unicode__(self):
return u"Matricula %s %s" % (self.alumno, self.ano_lectivo)
确切的错误来自一个名为“Octavo de Básica”的“Nivel”对象,如果没有 UnicodeDecodeError,我将无法使用它。
这是错误:
UnicodeDecodeError at /sisacademico/matricular_grupo/
'ascii' codec can't decode byte 0xc3 in position 20: ordinal not in range(128)
...
The string that could not be encoded/decoded was: de B��sica
编辑:发现错误
好的,我发现了我的错误,我不会删除问题,因为 django 给我的错误 (UnicodeDecodeError) 完全是误导性的。错误是这个:
nivel_obj = Nivel.objects.filter(id=nivel_id) <---
nueva_matricula = Matricula(nivel=nivel_obj, ano_lectivo=ano_lectivo, alumno=a)
我无法使用 nivel=queryset 而不是 nivel=NivelObject 保存新对象。
应该是:
nivel_obj = Nivel.objects.get(id=nivel_id)
我的错。
但是,为什么 django 会给我一个 UnicodeDecodeError?!!
【问题讨论】:
-
一般来说,这对我来说都是正确的。您应该为
Matricula上的verbose_name属性使用Unicode 文字,例如verbose_name = u'matrícula',但我不明白为什么这会产生您所看到的异常。UnicodeDecodeError来自于当编码字符串包含非 ascii 字符时尝试混合编码字符串和 Unicode 对象,例如'matr\xc3\xadcula' + u'matrícula',因此某处正在获取名称的编码版本。 Django 自己不会这样做 - 如果您可以显示您的视图代码,我或其他读者可能会帮助发现它。