首页 > 编程问答 >Django 1.9 教程 __str__ () 不起作用

Django 1.9 教程 __str__ () 不起作用

时间:2024-07-30 12:12:11浏览次数:10  
标签:python django python-3.x django-1.9

我正在尝试使用 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__() 方法应该可以正常工作。

标签:python,django,python-3.x,django-1.9
From: 35137105

相关文章

  • 在家用电脑上设置 Python 和 Jupyter,尝试打开 Jupyter 笔记本并显示错误,无法获取
    我有最新的Python版本3.12.4和以下版本的Jupyter:SelectedJupytercorepackages...IPython:8.26.0ipykernel:6.29.5ipywidgets:notinstalledjupyter_client:8.6.2jupyter_core:5.7.2jupyter_server:2.14.2jupyterlab......
  • Python - Reloading a module
    Eachmoduleisloadedintomemoryonlyonceduringaninterpretersessionorduringaprogramrun,regardlessofthenumberoftimesitisimportedintoaprogram.Ifmultipleimportsoccur,themodule’scodewillnotbeexecutedagainandagain.Suppose......
  • vscode python 3.7 pylance debugpy 插件 vsix
    可能报错  crashed5timesinthelast3minutes.Theserverwillnotberestarted.  ---pylance 可能报错  cannotreadpropertiesofundefinedreadingresolveEnvironment   --- debugger可能      vscodepython3.7调试没有反应......
  • Python获取秒级时间戳与毫秒级时间戳的方法[通俗易懂]
    参考资料:https://cloud.tencent.com/developer/article/21581481、获取秒级时间戳与毫秒级时间戳、微秒级时间戳代码语言:javascript复制importtimeimportdatetimet=time.time()print(t)#原始时间数据print(int(t))......
  • CEFPython
    在Tkinter界面中直接嵌入Selenium的浏览器视图并不是一件直接的事情,因为Selenium本身并不提供图形界面嵌入的功能。Selenium主要用于自动化web浏览器,但它并不直接控制浏览器窗口的显示方式,而是依赖于WebDriver来与浏览器交互。然而,你可以使用一些替代方案来在Tkinter应用中模拟或......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-58 - 文件下载
    1.简介前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件。因此宏哥就接着讲解和分享一下:自动化测试下载文件。可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就是访问到下载页面,然后定位到要下载的文件的下载按钮后,点击按钮就可以了。其实......
  • Python - Function Annotations
     deffunc(s:str,i:int,j:int)->str:returns[i:j]Theparametersissupposedtobeastring,soweplaceacolonaftertheparameternameandthenwritestr.Parametersiandjaresupposedtobeintegerssowewriteintforthem.Returntypeis......
  • 使用带有 pythonKit XCODE 的嵌入式 Python,在 iOS 应用程序中与 OpenCV-python 签名不
    我根据Beewares使用指南在XCODE中将Python嵌入到我的iOS项目中https://github.com/beeware/Python-Apple-support/blob/main/USAGE.md运行时,我得到pythonKit找不到由ultralytics导入的cv2错误。当我将OpenCV-python添加到我的app_packages文件夹时......
  • Python - Arguments and Parameters
    ParametersinFunctionDefinitionA.deffunc(name):MatchbypositionorbynameB.deffunc(name=value):DefaultargumentC.deffunc(*args):CollectextrapositionalargumentsintuplenamedargsD.deffunc(**kwargs):Collectextrakeywordargumentsi......
  • Python MySQL 无法连接,原因不明
    当我尝试使用python连接到我的MySQL数据库时,由于未知原因显示错误:dTraceback(mostrecentcalllast):File"/usr/local/bin/flask",line8,in<module>sys.exit(main())^^^^^^File"/usr/local/lib/python3.12/site-packages/flask/cli.py&......