无论我做什么,Django 都会出现 ImportError
我刚开始玩Django,决定在我的服务器上试试。所以我安装了Django,并按照Djangoproject.com上的教程创建了一个新项目。
不幸的是,无论我怎么做,我都无法让视图正常工作:我总是收到
ImportError at /
No module named index
我一直在谷歌上搜索,尝试各种命令,但都没有成功,我快要抓狂了,感觉自己快秃了。我尝试把Django的源目录、我的项目目录和应用目录添加到PYTHONPATH,但还是不行。我也确保在所有目录中都有init.py文件(项目和应用的目录都有)。有没有人知道这里可能出什么问题?
更新
抱歉,我发这个的时候有点急,这里补充一些背景:
我尝试的服务器是Django自带的服务器,使用manage.py(python manage.py 0.0.0.0:8000,因为我需要外部访问)在Linux(Debian)上运行。
appdir/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Sup")
def test(request):
return HttpRespons("heyo")
urls.py
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^****/', include('****.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^test/', include('mecore.views.test')),
(r'^', include('mecore.views.index'))
)
3 个回答
来自 ImportError No module named views 的内容:
试着把
views.py
文件移动到 "内层" 的 mysite 目录里。因为视图是应用程序的一部分,所以需要把它放在应用程序的目录里,而不是项目的目录里。你看到的错误信息说明
mysite
(这个应用)里没有views.py
这个模块。
你在 mecore 和 views 目录里都有 __init__.py
文件吗?还有在 views 里有一个 index.py 吗?
从 Python 的角度来看,只有当一个目录里有一个叫 __init__.py
的文件时,它才算是一个包(这个文件可以是空的,如果你不需要在导入这个包时执行任何特别的代码,但这个文件必须存在)。
补充一下:在 include
中,你必须指定一个模块的 Python 路径,而不是一个函数的路径:请查看 Django 的相关文档 -- 从你的评论来看,你似乎在错误地使用 include
,正如 @S.Lott 在他的回答中所推测的那样。
你的 urls.py
文件有问题;你应该看看 这个链接 和 这个链接。
你不是在引入一个函数,而是在引入一个模块。你需要指定一个函数,比如 mecore.views.index
。你只需要引入整个模块,比如 include('mecore.views')
。
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^****/', include('****.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^test/', 'mecore.views.test'),
(r'^', 'mecore.views.index')
)