views:

186

answers:

2

I am working through the Django tutorials, and now I am at creating a poll.

The code below works fine until I want to create choices, where for some reason I always get this error message:

line 22, in __unicode__
return self.question

AttributeError: 'Choice' object has no attribute 'question'

What am I doing wrong?

Here's my code:

import datetime
from django.db import models

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.question # this is line 22
+4  A: 

It should be:

def __unicode__(self):
    return self.poll.question

Because poll is a related model that contains the question.

aeby
+1  A: 

The __unicode__ method on the Choice model should look something like:

def __unicode__(self):
    return self.poll.question

question attribute does not exist on the Choice model, you need to reach for it over the poll foreign key field.

Don't forget to check out Django's great documentation that shows many examples on how to handle many to one relationships.

Edit

It would probably make more sense to return self.choice in Choice model __unicode__ method so it outputs the actual choice not the Poll question.

def __unicode__(self):
    return self.choice
rebus
I did that and now I get these responses:>>> Poll.objects.all()[<Poll: What's up?>]>>> Poll.objects.get(pk=1)<Poll: What's up?>>>> p=Poll.objects.get(pk=1)>>> p.choice_set.all()[<Choice: What's up?>, <Choice: What's up?>]>>> p.choice_set.create(choice='Not much', votes=0)<Choice: What's up?>>>> it should not have choices at the beginning, because I did not set any choices. Thanks for the documentation link!I will check it.
MacPython
True, i guess it would be silly to have something like `return self.poll.question` for output, try `return self.choice`
rebus
Thanks for the answers! I cant say for sure if the return.self.choice is the solution because for some other reason the main_page wont show up now. So I have to solve that and close this question for now. Thanks again! This is the best site I have encountered so far. Really helpful!
MacPython
The return self.poll.question version worked! Thanks again!!!
MacPython