Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin UnicodeDecodeError when adding

I'm having problems when adding elements in 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)

When adding a VisitType object in the admin site, there is no problem. adding_VisitType

But, when adding a Visit in the admin: adding_Visit

I get the UnicodeDecodeError with this hint: "The string that could not be encoded/decoded was Analtica" (notice that I used the "Analítica" Visit Type in the form.

I'm using django 1.5.1, MySQL-python 1.2.4.

The MySQL is using tables with the utf8_general_ci collation.

The database is a MySQL 5.5.30.

Regards.

like image 584
Axel Avatar asked Dec 26 '22 00:12

Axel


1 Answers

Neither of your __unicode__ methods return unicode strings. They both return byte strings. This is a recipe for disaster. Especially when inside those functions you're interpolating 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)
like image 62
Daniel Roseman Avatar answered Jan 01 '23 22:01

Daniel Roseman