python - 类型错误 : view must be a callable or a list/tuple when including another urls. py

标签 python django django-urls django-1.11

我仔细阅读了涉及该主题的其他几个问题,但是没有一个描述 include() 的情况(包括另一个 urls.py 文件)。我还查看了 1.11 文档 here并按照编码进行编码,但是,我不断收到错误“TypeError:在 include() 的情况下, View 必须是可调用的或列表/元组。”尝试了这个答案和其他两个答案的几乎所有推导,但都无济于事。我的错误/误解在哪里?

url.py

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

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

atfl/urls.py 中的代码

from django.conf.urls import url
from atfl.views import home, people

urlpatterns = [
    url(r'^$', 'home', name='home'),
    url(r'^people/$', 'people', name='people'),
]

atfl/views.py 中的代码

from django.shortcuts import render_to_response

def index(request):
    return render_to_response('atfl/home.html', {})

def LoadTextFile(request):
    return render_to_response("atfl/people.html", {})

最佳答案

错误不是来自 include,而是来自 urls.py 中的字符串 'home''people'正在尝试包括。使用您已经导入的 View :

from atfl.views import home, people

app_name = 'atfl'

urlpatterns = [
    url(r'^$', home, name='home'),
    url(r'^people/$', people, name='people'),
]

修复该问题后,include 中存在一个需要修复的错误。命名空间是 include 的参数,即 include('atfl.urls', namespace='atfl')。您可以将其作为 url() 的参数。但是,在这种情况下,您应该从该 URL 模式中完全删除命名空间,并将 app_name 添加到应用的 urls.py,如上所示。

url(r'^atfl/', include('atfl.urls')),

最后,不要使用render_to_response。它已经过时了。请改用 render

from django.shortcuts import render_to_response

def index(request):
    return render(request, 'atfl/home.html', {})

关于python - 类型错误 : view must be a callable or a list/tuple when including another urls. py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50042581/

相关文章:

Django 站点 - 两个站点的不同 urls.py

python - 导入错误 : No module named http django

python - 使用 Python 从个人 OneDrive 下载文件

python - 如何在 Django 中使用管道压缩特定文件?

Django:阻止外部查询字符串请求

python - Django-2.2 NoReverseMatch 错误。无法重定向到下一页

python - 将变量 urlname 传递给 django 模板中的 url 标签

python - 解析 CS :GO script file in Python

python - 从多个 OHLCV 数据帧创建单个 pandas 数据帧

Django Queryset-仅从查询中的datetime字段中提取日期(在.value()内部)