【问题标题】:Error import views in urls.pyurls.py 中的错误导入视图
【发布时间】:2015-10-17 02:06:03
【问题描述】:

我不明白为什么这条线会失败:from library import views

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()),
]

文件views.py

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

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

【问题讨论】:

  • 在你的第一个例子中不应该是views.IndexView.as_view()吗?
  • 错误的全文是什么?
  • @alecxe 是的,你是对的
  • @FranciscoGarcía 阅读完整的错误消息仔细会告诉你错误在哪一行,以及确切的错误是什么。 from library import views 行没有失败,是 urlpattern[0] 的定义失败了。

标签: python django django-views django-urls


【解决方案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
    ]

【讨论】:

    猜你喜欢
    • 2022-12-14
    • 2013-10-28
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2014-10-20
    • 2011-04-14
    相关资源
    最近更新 更多