5

我正在阅读“The Django Book”,但不断收到错误消息“无法导入名称 current_datetime”

网址.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),
)

我的观点.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
4

1 回答 1

6

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

from mysite.views import current_datetime, hello

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

于 2013-04-11T22:47:40.563 回答