Python – Django Polls App: AttributeError: ‘Choice’ object has no attribute ‘question_text’


I was doing the tutorial on the Django website, when I got this error.
I am using OS X 10.10.

>>> q.choice_set.create(choice_text='Not much', votes=0)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/Django-1.7.8-py2.7.egg/django/db/models/", line 458, in __repr__
    u = six.text_type(self)
  File "/Users/anushrutgupta/Documents/IMG/Django/mysite/polls/", line 22, in __str__
    return self.choice_text
AttributeError: 'Choice' object has no attribute 'question_text'


import datetime

from django.db import models
from django.utils import timezone

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 >= -datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):   
        return self.choice_text

Is something wrong in the models?

Best Solution

Looks like a typo in your code on line 22 of, you have return self.question_text but it should be return self.choice_text.

EDIT: I see you are using Python 2.7, with Python 2 you need to use __unicode__ and not __str__.

__str__ or __unicode__?

On Python 3, it’s easy, just use __str__().

On Python 2, you should define __unicode__() methods returning unicode values instead. Django models have a default __str__() method that calls __unicode__() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a bytestring, with characters encoded as UTF-8. Python does the opposite: object has a __unicode__ method that calls __str__ and interprets the result as an ASCII bytestring. This difference can create confusion.

If all of this is gibberish to you, just use Python 3.

Related Question