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)

Advertisement

Intro to Security

The class I’m most excited about this semester is Computer Security. Our first project was modeled after Capture The Flag contests where you have to pass level N-1 to get to level N, etc. It was a straightforward assignment: 4 levels and brute force our way to find all 4 flags. 

The first two levels were files encrypted with dictionary words and easy to decrypt. The third level was bit more involved i.e. some steganography and encoded text contained in an encrypted file while the fourth was an encrypted file contained in an encrypted file. Thankfully, the steganography was more of stuffing extra metadata into the image than modifying the least significant bit or any of the most complex steganography tactics. Also, on the recommendation of our professor, I used the nice python-gnupg module to do much of the heavy lifting. There’s a Java library out there that integrates with GPG but I haven’t been able to make sense of it. 

Side note: Python is really nice to use. I’ve resumed my Python tutorial on CodeAcademy.com and I’m going through Zed Shaw’s Learn Python The Hard Way course.Â