3

我正在尝试使用 Win 10 操作系统和 Python 3.5 的 Django 1.9 教程,而 Django 版本是 1.9。我已经成功地在“问题”和“选择”中创建并存储了值。在此之后,当我__str__()按照教程django tutorial 2更改 polls/model.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'

我的民意调查\models.py 是:

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
4

4 回答 4

5

您的问题模型中很可能没有question_text字段。您可能在添加__str__方法定义时已将其删除。

检查你是否有这个:

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

    def __str__(self):
        return self.question_text
于 2016-02-01T18:04:20.093 回答
0

如果您正在关注 Django 文档,那么您的结果是一些错字。只需重做模型部分并运行 makemigration 和 migrate cmd。它应该工作。我遇到了同样的问题,然后我只是从 Django 文档中复制并粘贴了代码,它就可以工作了。

于 2018-12-19T19:10:34.967 回答
0

做这个。

def __repr__ (self):
    return self.title

重新启动外壳/会话。

然后检查。

于 2020-05-02T19:13:42.870 回答
0

我也遇到了同样的问题,但后来我检查了我忘记添加双引号而不是单_输入__str__

于 2022-01-07T13:37:18.680 回答