Django教程中的pub_date无效错误

-4 投票
2 回答
2671 浏览
提问于 2025-04-17 14:55

在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则被满足时,程序才会继续运行。

比如说,你可能希望程序在用户输入正确的密码后才能进入系统。这个时候,你就需要用到“条件语句”。条件语句就像是一个检查点,程序会在这里停下来,看看条件是否成立。如果条件成立,程序就会继续执行;如果不成立,程序可能会给出提示,或者直接停止。

在不同的编程语言中,条件语句的写法可能会有所不同,但它们的基本原理是一样的。你只需要记住,条件语句帮助程序做出决策,让它能根据不同的情况采取不同的行动。

所以,理解条件语句是编程的基础之一,它能让你的程序变得更加智能和灵活。

C:\mysite>python manage.py shell
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Poll,Choice
>>> Poll.objects.all()
[]
>>> import django
>>> from django.utils import timezone
>>> p= Poll(question="what's new?",pub_date= timezone.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 367, in __init__
    raise TypeError("'%s'is an invalid keyword argument for
                          this function"%kwargs.keys()   [0])
TypeError: 'pub_date' is an invalid keyword argument for this function

2 个回答

2

检查一下你的 models.py 文件,可能是你在 pub_date 这个日期时间字段上打错了字。

1

虽然有点晚,但我也遇到过这个问题,最后找到了答案。你需要把你的 models.py 文件改成这样:

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

撰写回答