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/base.py", line 458, in __repr__
u = six.text_type(self)
File "/Users/anushrutgupta/Documents/IMG/Django/mysite/polls/models.py", line 22, in __str__
return self.choice_text
AttributeError: 'Choice' object has no attribute 'question_text'
>>>
My models.py:
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 >= timezone.now() -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?
Looks like a typo in your code on line 22 of models.py
, 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 thatunicode(p)
will return a Unicode string, andstr(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With