3

I am trying Django 1.9 tutorial with Win 10 os and Python 3.5 and Django version is 1.9. I have successfully created and stored values in "Question" and "Choice". After this when i have changed polls/model.py with __str__() as per tutorial django tutorial 2. I am getting this error:

>>> from polls.models import Question, Choice
>>> Question.objects.all()
Traceback (most recent call last):
  File "C:\newenv\lib\site-packages\django\core\management\commands\shell.py", line 69, in handle
    self.run_shell(shell=options['interface'])
  File "C:\newenv\lib\site-packages\django\core\management\commands\shell.py", line 61, in run_shell
    raise ImportError
ImportError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\newenv\lib\site-packages\django\db\models\query.py", line 237, in __repr__
    return repr(data)
  File "C:\newenv\lib\site-packages\django\db\models\base.py", line 459, in __repr__
    u = six.text_type(self)
  File "C:\newenv\mysite_new\polls\models.py", line 8, in __str__
    return self.question_text
AttributeError: 'Question' object has no attribute 'question_text'

my polls\models.py is:

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text
bakkal
  • 54,350
  • 12
  • 131
  • 107
Maitray Suthar
  • 263
  • 2
  • 13

4 Answers4

6

You most likely do not have question_text field in your Question model. You may have deleted it when you added the __str__ method definition.

Check that you have this:

class Question(models.Model):
    question_text = models.CharField(max_length=200) # <--- Double check you have this

    def __str__(self):
        return self.question_text
bakkal
  • 54,350
  • 12
  • 131
  • 107
0

If you are following the Django documentation, then it is some typo at your end. Just redo the model part and run the makemigration and migrate cmd. It should work. I faced the same issue and then I just copied and pasted the code from Django documentation and it worked.

0

Do this.

def __repr__ (self):
    return self.title

restart the shell/session.

then check.

TrickyJ
  • 61
  • 2
0

I was also getting the same problem but then I checked I forget to adddouble inverted comma instead of single _ in __str__

Shunya
  • 2,344
  • 4
  • 16
  • 28