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

时间:2015-07-27 01:28:05

标签: python django django-views django-urls

我不明白为什么这行失败了:来自库导入视图

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

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

但这不是:来自library.views导入IndexView

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

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

file views.py

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

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

1 个答案:

答案 0 :(得分:1)

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

    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
    ]