我正在尝试使用 Win 10 操作系统和 Python 3.5 的 Django 1.9 教程,Django 版本是 1.9。我已成功在“问题”和“选择”中创建并存储值。之后,当我按照教程
__str__()
django教程2
更改了polls/model.py时。我收到此错误:
我的 polls\models.py 是:
>>> 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
遇到的错误是因为代码中的
Question
模型没有名为
question_text
的属性。似乎忘记在
Question
模型中定义
question_text
字段。
请修改的
polls/models.py
文件,确保
Question
模型定义了
question_text
字段,如下所示:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200) # Add this line
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
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
注意:
确保在
settings.py
文件的
INSTALLED_APPS
中包含 'polls' 应用。
修改完模型后,请运行以下命令以应用更改:
python manage.py makemigrations polls
python manage.py migrate
现在,的
Question
对象应该有一个
question_text
属性,并且
__str__()
方法应该可以正常工作。