Django错误:无法导入名称current_datetime

时间:2013-04-11 21:01:24

标签: python django datetime

我正在阅读“Django Book”并且我一直收到错误“无法导入名称current_datetime”

Urls.py:

from django.conf.urls.defaults import patterns, include, url
from mysite.views import current_datetime, hello

urlpatterns = patterns('', 
    ('^hello/$', hello), 
    ('^time/$', current_datetime),
    (r'^time/plus/(\d{1,2})/$', hours_ahead),
)

我的Views.py:

from django.http import HttpResponse
import datetime

def hello(request):
    return HttpResponse("Hello world")

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

我的工作目录:

./mysite:
__init__.py manage.py   mysite      views.py

无论我做什么,我都会在urls.py第2行得到相同的导入错误,关于current_time:

Environment:


Request Method: GET
Request URL: http://localhost:8000/

Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  103.                     resolver_match = resolver.resolve(request.path_info)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in resolve
  319.             for pattern in self.url_patterns:
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in url_patterns
  347.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
  342.             self._urlconf_module = import_module(self.urlconf_name)
File "/Library/Python/2.7/site-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/Users/jvieitez/Code/djcode/mysite/mysite/urls.py" in <module>
  2. from mysite.views import hello, current_datetime, hours_ahead

Exception Type: ImportError at /
Exception Value: cannot import name current_datetime

1 个答案:

答案 0 :(得分:6)

您的工作目录出了问题。 manage.py和views.py不应位于同一目录中。我建议将内部mysite重命名为其他内容,这样可以避免混淆,而views.py应该位于 inner mysite目录中。你说

from mysite.views import current_datetime, hello

但是views.py不在mysite目录中。这就是问题所在。