首页 > 解决方案 > TypeError:“模块”对象不可调用 Django 3 渲染函数

问题描述

我只是在我的 Django 3 应用程序中创建一个简单的 hello world 页面,但出现错误

TypeError: 'module' object is not callable

这是错误

TypeError at /
'module' object is not callable
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.0.11
Exception Type: TypeError
Exception Value:    
'module' object is not callable
Exception Location: C:\Users\admin\AppData\Roaming\Python\Python37\site- packages\django\template\context.py in bind_template, line 246
Python Executable:  C:\Program Files (x86)\Microsoft Visual 
Studio\Shared\Python37_64\python.exe
Python Version: 3.7.8
Python Path:    
['C:\\Users\\admin\\Repositories\\django-docker\\django-portal-base\\app',
'C:\\Program Files (x86)\\Microsoft Visual '
'Studio\\Shared\\Python37_64\\python37.zip',
'C:\\Program Files (x86)\\Microsoft Visual 
Studio\\Shared\\Python37_64\\DLLs',
 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib',
 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64',
 'C:\\Users\\admin\\AppData\\Roaming\\Python\\Python37\\site-packages',
 'C:\\Program Files (x86)\\Microsoft Visual '
 'Studio\\Shared\\Python37_64\\lib\\site-packages']
 Server time:   Thu, 14 Jan 2021 19:15:32 +0000

它以前可以工作,但现在突然不工作了。这是我的views.py

from django.shortcuts import render
# from django.http import HttpResponse
# from django.template import RequestContext, loader
# from django.template import Context

def index(request):
    """Placeholder index view"""
    print('XXXX')
    return render(request, 'hello_world/index.html')
    #return HttpResponse('Hello, World!')

def test(request):
    context = {'foo': 'bar'}
    return render(request, 'hello_world/index.html', context) 

错误是一致的,return render(request, 'hello_world/index.html')但是当我将其更改为它时,return HttpResponse('Hello, World!')它工作正常。

我的html文件很简单index.html

<h3> MY DJANGO APP</h3>

html文件也在正确的文件夹中templates/hello_world/index.html

设置

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': False,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            'django.contrib.sessions'
        ],
    },
},
]

标签: python-3.xdjangodjango-3.0

解决方案


django.contrib.sessions不是可调用对象,因此它不是有效的上下文处理器。

事实上,它是一个应用程序,因此,它应该在您的INSTALLED_APPS列表中,而不是在TEMPALTES context_processors列表中。从那里删除它应该可以解决此问题。


为什么会这样?

异常提到它发生在django/template/context.py第 246 行(在 Django v3.0.11 中)。如果您在第 246 行看到源代码,您可以看到在这一行 Django 正在运行已注册的模板上下文处理器。由于,django.contrib.sessions不是可调用对象,而是模块,因此您会收到以下异常消息:'module' object is not callable.


推荐阅读