Django admin UnicodeDecodeError when adding

I am having problems adding elements to the django interface. I have two definitions:

# -*- coding: utf-8 -*- class VisitType(models.Model): name=models.CharField(max_length=50,db_index=True,verbose_name="Nombre del tipo de visita") is_basal=models.BooleanField(default=False,verbose_name="Es basal") def __unicode__(self): if self.is_basal: s="%s [BASAL]" % (self.name) else: s="%s" % (self.name) return s class Visit(models.Model): type=models.ForeignKey(VisitType,null=True,on_delete=models.SET(VisitType.get_sentinel_visit_type),db_index=False,verbose_name="Tipo de visita") def __unicode__(self): return "Tipo de visita %s" % (self.type) 

There is no problem adding a VisitType object to the admin site. add_VisitType

But when adding a visit to the admin: add_Visit

I get a UnicodeDecodeError with this hint: "The string that cannot be encoded / decoded was Analtica" (note that I used the "Visit Type" on the form.

I am using django 1.5.1, MySQL-python 1.2.4.

MySQL uses utf8_general_ci sorted tables.

The database is MySQL 5.5.30.

Sincerely.

+4
source share
1 answer

None of your __unicode__ methods return Unicode strings. Both return byte strings. This is a recipe for disaster. Especially when inside these functions you interpolate Unicode into byte strings.

Do this instead:

 def __unicode__(self): if self.is_basal: s = u"%s [BASAL]" % (self.name) else: s = self.name return s 

and

 return u"Tipo de visita %s" % (self.type) 
+10
source

Source: https://habr.com/ru/post/1492293/


All Articles