[Answered ]-Django UnicodeDecodeError in model object

1👍

filter isn’t doing what you want it to here:

nivel_obj = Nivel.objects.filter(id=nivel_id)

filter returns a queryset, not a single object. You can’t use it as the value of the ForeignKey field. I don’t yet see why that would raise the exception you’re reporting, maybe something not stringifying correctly while it’s trying to report the exception?

Normally you’d use get to get a single object rather than a queryset, or in a view sometimes the get_object_or_404 shortcut. But you don’t need to do that just to set a foreign key relationship – you can instantiate directly with the ID value:

nueva_matricula = Matricula(nivel_id=nivel_id, ano_lectivo=ano_lectivo, alumno=a)
nueva_matricula.save()

If your error persists, I would focus on checking the return type of self.nombre. Django CharFields should always return a Unicode object, but if you’ve got something really nonstandard happening and you’re getting an encoded bytestring as nombre, your __unicode__ method will throw the UnicodeDecodeError shown. But that shouldn’t be possible with standard Django.

1👍

The UnicodeDecodeError could be a really hard headache. Could be a lot of reasons.

You could try with some of this:


If you are using MySQL as database, you could use a command line like this to create it:

CREATE DATABASE `mydb` CHARACTER SET utf8 COLLATE utf8_general_ci;

See more here.


When you create the Nivel object with the nombre value ‘Octavo de Básica’, you could try something like this:

nivel_obj = Nivel(
    nombre=unicode('Octavo de Básica', 'utf-8'),
    ...
)

Read more here.


You could also try the encode Python function. here a tutorial

👤Gocht

Leave a comment