[Fixed]-TypeError 'x' object has no attribute '__getitem__'

30๐Ÿ‘

โœ…

Your issue is that your __unicode__ functions are returning model objects when they need to be returning unicode strings.

You can achieve this by adding the unicode() function to your __unicode__ methods:

class CampCon(models.Model):
    campsite = models.ForeignKey(CampSite)
    trip = models.ForeignKey('Trip')
    Date = models.DateField()
    user = models.ForeignKey(User)
    overall_review = models.TextField()
    facilities_review = models.IntegerField()
    things_to_do = models.IntegerField()
    privacy = models.IntegerField()
    beauty = models.IntegerField()
    overall_rating = models.IntegerField()

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

class ImageDB(models.Model):
    campsite = models.ForeignKey(CampSite)
    user = models.ForeignKey(User)
    description = models.CharField(max_length=200)
    image = models.ImageField(upload_to='/home/bobby/Pictures/CampThat')
    date_uploaded = models.DateField()
    date_taken = models.DateField()
    trip = models.ForeignKey('Trip')
    activity = models.ForeignKey(Activities)

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

This will call CampSite.__unicode__ which will return campsite.name.

2๐Ÿ‘

Use this method instead:

   def __unicode__(self):
        return unicode(self.campsite)
๐Ÿ‘คsantiagobasulto

0๐Ÿ‘

This also happens if you do it like this:

event_name = CharField(max_length = 250)

and not like this: (the right way)

event_name = models.CharField(max_length = 250)

might be helpful to someone

๐Ÿ‘คRamez Ashraf

0๐Ÿ‘

Since this is the first hit on Google: I got a similar error ('ItemGroup' object has no attribute '__getitem__') when doing the following:

class ItemGroup(models.Model):
    groupname = models.CharField(max_length=128)

    def __unicode__(self):
        return "%s" % self.groupname

class Item(models.Model):
    name = models.CharField(max_length=128)
    group = models.ForeignKey(MedGroup, verbose_name="Groep")

    def __unicode__(self):
        return "%s (%s)" % (self.name, self.group[:10])

The last line is wrong.

It was fixed by replacing that line to return "%s (%s)" % (self.name, self.group.groupname[:10])

๐Ÿ‘คSaeX

Leave a comment