Django: ‘long’ object has no attribute ‘encode’

Not the movie 🙂

I’m following the Django tutorial and it’s surprisingly fun! I ran into an issue that I’m going to document here for any hapless souls that come after me. To seasoned Python devs, it’s blindingly obvious but I’m a newbie. 

In the tutorial, we’re only supposed to create 2 models (Poll and Choice) but I decided to add an extra model to my models.py file:

    class Transaction(models.Model):
        groceryitem = models.IntegerField()
        store_name = models.CharField(max_length=255)
        transaction_id = models.IntegerField(default=1)
        purchase_date = models.DateTimeField(‘date purchased’)
        def __unicode__(self):
            return self.transaction_id

After adding the Transaction model to the admin page to be edited, I was unable to view 127.0.0.1:8000/admin/poll/transaction/ and got this error message:

Exception Type: AttributeError
Exception Value: ‘long’ object has no attribute ‘encode’

When i switched to the interactive shell to check on my Transaction objects, I got this very helpful error message.

>>> Transaction.objects.all():

[…]

TypeError: coercing to Unicode: need string or buffer, long found

When I defined __unicode__ for the Transaction model, I should output a string object instead of the number. Defining __unicode__ is analogous to defining the toString() method in Java (correct me if I’m wrong). To solve y The last line of my Transaction model group of statements should have been:

return str(self.transaction_id)

Advertisements

3 thoughts on “Django: ‘long’ object has no attribute ‘encode’”

  1. thanks it helped me too, the error i was getting is “long object has no attribute replace” when i was trying to delete an entry in the django admin,i was doing the same thing
    def __unicode__(self):
    return self.pk
    and i changed it to
    def __unicode__(self):
    return str(self.pk)
    and the issue was solved 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s