Django 1.9 tutorial __str__ () not working

Question:

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:newenvlibsite-packagesdjangocoremanagementcommandsshell.py", line 69, in handle
    self.run_shell(shell=options['interface'])
  File "C:newenvlibsite-packagesdjangocoremanagementcommandsshell.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:newenvlibsite-packagesdjangodbmodelsquery.py", line 237, in __repr__
    return repr(data)
  File "C:newenvlibsite-packagesdjangodbmodelsbase.py", line 459, in __repr__
    u = six.text_type(self)
  File "C:newenvmysite_newpollsmodels.py", line 8, in __str__
    return self.question_text
AttributeError: 'Question' object has no attribute 'question_text'

my pollsmodels.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
Asked By: Maitray Suthar

||

Answers:

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
Answered By: bakkal

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.

Answered By: Samcs099

Do this.

def __repr__ (self):
    return self.title

restart the shell/session.

then check.

Answered By: TrickyJ

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

Answered By: SIDDHANT MESHRAM

Maybe you are getting the error because you don’t have proper indentation. I got the same error when I didn’t have proper indentation. Now it’s correct. Inside the class you should declare the function as following:

class Position(models.Model):
   title = models.CharField(max_length=50)
   def __str__(self):
       return self.title
Answered By: Akshay Babu