I am working on the Django app poll as a way to go back to basics and learn Django using the documentation.
I got stuck pretty early on in Part 2, which highlighted to me how easy it is to add the wrong code into the wrong place and not even see it!
I had to include a choice for my poll, an answer to the question “What’s up?” – one choice is “Not much” but when I went to add it in shell
>>> q.choice_set.create(choice_text='Not much', votes=0)
I received an Attribute Error which was :
“Attribute Error: ‘Choice’ object has no attribute ‘question_text’
Here is my code:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text # CORRECT
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.question_text # INCORRECT
The error occurred because in the very last line
return self.question_text
it should actually be
return self.choice_text
Instead of the code expecting a choice to a question, I had the code believe it was expecting a question text.
I had copied the same return as the Question function and I don’t even remember doing it!
Once I made the change to choice_text everything worked fine.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
When it comes to writing code it is really easy to add a letter, miss out a comma, or repeat something you are not meant to and what I am learning is if there is an error, it’s always me – not the code!