Python导入可以工作,但是使用导入的项失败。使用Django,但这看起来像是一个新手Python问题

2021-04-12 00:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在浏览Django tutorial。在

我有这个档案

R:\jeffy\programming\sandbox\python\django_files\tutorial\django_test\...
...django_test\article\views.py

内容:

^{pr2}$

这个文件:

R:\jeffy\programming\sandbox\python\django_files\tutorial\django_test\...
...django_test\urls.py

内容:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from article.views import hello

urlpatterns = patterns('',
#    url(r'^hello/', include(article.views.hello)),
    url(r'^admin/', include(admin.site.urls)),
)

我启动Django服务器

python manage.py runserver

然后去

http://127.0.0.1:8000

它起作用了:

root success

就像这样

http://127.0.0.1:8000/admin

enter image description here

但是当我取消对“hello”行的注释时,它失败了:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from article.views import hello

urlpatterns = patterns('',
    url(r'^hello/', include(article.views.hello)), # <--Problem line
    url(r'^admin/', include(admin.site.urls)),
)

enter image description here

错误说

R:\\jeffy\\programming\\sandbox\\python\\django_files\\tutorial\\django_test

在PYTHONPATH中,“article”文件夹位于目录下。在

另外,为什么import article行没有导致错误,但是调用hello函数却失败了。在


请帮帮我。我错过了什么?在


更新

任何导入都不会以相同的方式失败(NameError at / name 'article' is not defined):

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^hello/', include(article.views.hello)),   # <-- Problem line
    url(r'^admin/', include(admin.site.urls)),
)

仅使用import article会导致以下错误:AttributeError at / 'module' object has no attribute 'views'

from django.conf.urls import patterns, include, url
from django.contrib import admin
import article

urlpatterns = patterns('',
    url(r'^hello/', include(article.views.hello)),   # <-- Problem line
    url(r'^admin/', include(admin.site.urls)),
)

取消导入并将调用放入字符串中(如建议),结果是ImportError at / No module named 'article.views.hello'; 'article.views' is not a package

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^hello/', include(article.views.hello)),   # <-- Problem line
    url(r'^admin/', include(admin.site.urls)),
)

最后,直接导入hello函数:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from article.views import hello

urlpatterns = patterns('',
    url(r'^hello/', include(hello)),
    url(r'^admin/', include(admin.site.urls)),
)

这样,调用http://127.0.0.1:8000失败,但以预期的方式

enter image description here

但接下来,http://127.0.0.1:8000/hello失败了:

enter image description here