Django coercing to Unicode: need string or buffer, NoneType found


This errors in Django ‘coercing to Unicode: need string or buffer, NoneType found’ take me 20 minutes to solved.
Look at our example models :

1
2
3
4
5
class Insurance(models.Model):
    code = models.CharField(max_length=255, blank=True, null=True, default=None, unique=True)

class Person(models.Model):
    insurance = models.ForeignKey(Insurance)

When insurance value is None, then you will get error :

1
coercing to Unicode: need string or buffer, NoneType found

The solution ?

If we want to still showing “None” value, then :

1
2
3
4
5
class Insurance(models.Model):
    code = models.CharField(max_length=255, blank=True, null=True, default=None, unique=True)

    def __unicode__(self):
        return unicode(self.code)

Or, we can exclude(code=None) in Form ModelChoiceField() that related with this models.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.