[Django]-Coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

92👍

This error happens when you have a __unicode__ method that is a returning a field that is not entered. Any blank field is None and Python cannot convert None, so you get the error.

In your case, the problem most likely is with the PCE model’s __unicode__ method, specifically the field its returning.

You can prevent this by returning a default value:

def __unicode__(self):
   return self.some_field or u'None'

14👍

This error might occur when you return an object instead of a string in your __unicode__ method. For example:

class Author(models.Model):
    . . . 
    name = models.CharField(...)


class Book(models.Model):
    . . .
    author = models.ForeignKey(Author, ...)
    . . .
    def __unicode__(self):
        return self.author  # <<<<<<<< this causes problems

To avoid this error you can cast the author instance to unicode:

class Book(models.Model):
    . . . 
    def __unicode__(self):
        return unicode(self.author)  # <<<<<<<< this is OK

1👍

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

0👍

The return value def __unicode __ should be similar to the return value of the related models (tables) for correct viewing of “some_field” in django admin panel.
You can also use:

def __str__(self):
    return self.some_field

0👍

Replace the earlier function with the provided one. The simplest solution is:

def __unicode__(self):

    return unicode(self.nom_du_site)

-5👍

First, check that whatever you are returning via unicode is a String.

If it is not a string you can change it to a string like this (where self.id is an integer)

def __unicode__(self):
    return '%s' % self.id

following which, if it still doesn’t work, restart your ./manage.py shell for the changes to take effect and try again. It should work.

Best Regards

👤laycat

Leave a comment