TypeError:在include()的情况下,view必须是可调用的或list / tuple

时间:2016-07-15 11:05:53

标签: django python-2.7 python-3.x

我是django和python的新手。在URL映射到视图期间,我收到以下错误: TypeError:在include()。

的情况下,view必须是可调用的或list / tuple

网址。 py代码: -

from django.conf.urls import url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^posts/$', "posts.views.post_home"), #posts is module and post_home 
]                                              # is a function in view. 

views.py代码: -

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
#function based views

def post_home(request):
    response = "<h1>Success</h1>"
    return HttpResponse(response)

回溯

enter image description here

7 个答案:

答案 0 :(得分:26)

在1.10中,您无法再将导入路径传递给url(),您需要传递实际的视图功能:

from posts.views import post_home

urlpatterns = [
    ...
    url(r'^posts/$', post_home),
]        

答案 1 :(得分:2)

用此

替换您的管理网址模式
url(r'^admin/', include(admin.site.urls))

所以你的urls.py成为:

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


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^posts/$', "posts.views.post_home"), #posts is module and post_home 
] 

管理员网址可以通过include(1.9之前)调用。

答案 2 :(得分:1)

对于Django 1.11.2
在主urls.py中写道:

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

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^posts/', include("Post.urls")),
] 

在appname / urls.py文件中写:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$',views.post_home),
]

答案 3 :(得分:0)

答案在 project-dir / urls.py

Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))

答案 4 :(得分:0)

为了补充@knbk的答案,我们可以使用以下模板:

,如1.9:

from django.conf.urls import url, include

urlpatterns = [
    url(r'^admin/', admin.site.urls), #it's not allowed to use the include() in the admin.urls
    url(r'^posts/$', include(posts.views.post_home), 
] 

应该在1.10中:

from your_project_django.your_app_django.view import name_of_your_view

urlpatterns = [
    ...
    url(r'^name_of_the_view/$', name_of_the_view),
]

请记住在your_app_django&gt;&gt;中创建views.py用于渲染视图的函数。

答案 5 :(得分:0)

您需要传递实际的视图功能

来自posts.views导入post_home

urlpatterns = [     ...     url(r&#39; ^ posts / $&#39;,post_home), ]

这很好用! 您可以在URL Dispatcher Django阅读 在这里Common Reguler Expressions Django URLs

答案 6 :(得分:0)

您将需要导入post_home:

from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from posts.views import post_home

urlpatterns = [
    path('admin/', admin.site.urls),
    path('posts/',post_home),
]