我正在关注这个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仍然会给我这个错误?
答案 0 :(得分:3)
在 models.py :
文件的顶部添加此项import datetime
答案 1 :(得分:0)
您不仅需要调用datetime(因为它是文件夹),还需要调用当前代码中的 datetime.datetime
或将导入替换为
from datetime import datetime