coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

后端 未结 6 625
梦毁少年i
梦毁少年i 2020-12-07 22:32

I have this error since a long time but can\'t figure it out :

Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found

相关标签:
6条回答
  • 2020-12-07 22:40

    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

    0 讨论(0)
  • 2020-12-07 22:45

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

    def __unicode__(self):
    
        return unicode(self.nom_du_site)
    
    0 讨论(0)
  • 2020-12-07 22:48

    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'
    
    0 讨论(0)
  • 2020-12-07 22:51

    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 讨论(0)
  • 2020-12-07 22:57

    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
    
    0 讨论(0)
  • 2020-12-07 22:57

    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 讨论(0)
提交回复
热议问题