tags:

views:

244

answers:

4

I am just started out learning Python and also started looking into Django a little bit. So I copied this piece of code from the tutorial:

    # Create your models here.
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
     return self.question
    def was_published_today(self):
     return self.pub_date.date() == datetime.date.today()

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def ___unicode__(self):
     return self.choice   #shouldn't this return the choice

When I play around with it in the shell, I just get the "question" of the Poll object, but for some reason it won't return of the "choice" of the Choice objects. I fail to see the difference. My output on the shell looks like this:

>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>

I was expecting for the Choice objects to return something else than "Choice object". Does anybody have an idea about where I failed and what I should look into?

EDIT: Way to make me feel like an idiot. Yes, the three underscores were the problem. I was looking at that for about an hour now.

+6  A: 

You have three underscores before "unicode__" on the Choice class, it should be only two like in your Poll class, like this:

def __unicode__(self):
    return u'%s' % self.choice
J. Pablo Fernández
+3  A: 

Your unicode method has to many underscores, it should read:

def __unicode__(self):
    return u'%s' % self.choice
Gerry
Draw! ...okay, you were faster ;-)
Jon Cage
+2  A: 

Change:

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def ___unicode__(self):
        return self.choice   #shouldn't this return the choice

To:

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def __unicode__(self):
        return self.choice   #shouldn't this return the choice

You had too many underscores in the second __unicode__ definition

Jon Cage
+2  A: 

The official django book is a bit outdated. But the comments to the paragraphs are really useful.

___unicode__(self):

should be __unicode__(self):

Two underscores.

MrHus