Django教程:NameError:未定义全局名称'datetime'

时间:2017-09-09 02:07:05

标签: python django datetime

我正在关注这个Django教程:https://docs.djangoproject.com/en/1.11/intro/tutorial05/

当我运行python manage.py test polls时,我收到此错误:

======================================================================
ERROR: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/user/learning-django/mysite/polls/tests.py", line 18, in test_was_published_recently_with_future_question
    self.assertIs(future_question.was_published_recently(), False)
  File "/home/user/learning-django/mysite/polls/models.py", line 16, in was_published_recently
    return self.pubDate >= timezone.now() - datetime.timedelta(days=1)
NameError: global name 'datetime' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
Destroying test database for alias 'default'...

这是我的tests.py代码:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.utils import timezone
from django.test import TestCase

from .models import Question

import datetime

class QuestionModelTests(TestCase):
    def test_was_published_recently_with_future_question(self):
        """
        was_published_recently() returns `False`for questions whose pubDate is in the future
        """
        time=           timezone.now() + datetime.timedelta(days=30)
        future_question=Question(pubDate=time)
        self.assertIs(future_question.was_published_recently(), False)

为什么即使我import datetime中有tests.py,Django / Python仍然会给我这个错误?

2 个答案:

答案 0 :(得分:3)

models.py

文件的顶部添加此项
import datetime

答案 1 :(得分:0)

您不仅需要调用datetime(因为它是文件夹),还需要调用当前代码中的 datetime.datetime

或将导入替换为

 from datetime import datetime