在 urls.py 中导入视图时出错

Error import views in urls.py

我不明白为什么这行失败:from library import views

from django.conf.urls import include, url
from library import views

urlpatterns = [
    url(r'^$', IndexView.as_view()),
]

但这不是:from library.views import IndexView

from django.conf.urls import include, url
from library.views import IndexView

urlpatterns = [
    url(r'^$', IndexView.as_view()),
]

文件views.py

from django.shortcuts import render
from django.views.generic import TemplateView

class IndexView(TemplateView):
    template_name = "index.html"

您需要导入主要 class 本身而不是父项。

    from django.conf.urls import include, url
    from library import views

    urlpatterns = [
        url(r'^$', IndexView.as_view()), ## this will not work
        url(r'^$', views.IndexView.as_view()), ## OK
    ]

另一种情况

    from django.conf.urls import include, url
    from library.views import IndexView

    urlpatterns = [
        url(r'^$', IndexView.as_view()), ## OK
    ]