Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - TypeError: coercing to Unicode

Tags:

python

django

I'm getting TypeError: coercing to Unicode: need string or buffer, int found

This is my models.py:

class FollowingModel(models.Model):
    user = models.ForeignKey(User)
    person = models.IntegerField(max_length=20, blank=False)

    def __unicode__(self):
            return self.person

When I retrieve the values from the FollowingModel in my views like this

g = FollowingModel.objects.all()
g[0] -----> I'm getting that error

I tried changing the def __unicode__(self): as

def __unicode__(self):
    return str(self.person)

But no use, still I'm getting the same error. Could anyone guide me?

Thanks!

UPDATE

>>>g = FollowingModel.objects.all()
>>>g

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 72, in __repr__
return repr(data)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 370, in __repr__
u = unicode(self)
TypeError: coercing to Unicode: need string or buffer, int found
like image 735
rnk Avatar asked Jan 16 '23 06:01

rnk


1 Answers

The __unicode__ method should return just that, unicode:

def __unicode__(self):
    return unicode(self.person)
like image 89
Martijn Pieters Avatar answered Jan 18 '23 22:01

Martijn Pieters