我刚开始学习Django,并尝试向我的应用程序添加中间件。
在ProjectFolder / app下,我具有以下文件:
__init__.py
文件 MIDDLEWARE = (
'SimpleMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
class SimpleMiddleware(MiddlewareMixin):
def __init__(self, get_response):
print("***********************************SIMPLE MIDDLEWARE")
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
print("***********************************SIMPLE MIDDLEWARE")
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
def process_request(self, request):
print("***********************************SIMPLE MIDDLEWARE")
return None
from app import views
urlpatterns = [
path('hello', views.index, name='index'),
path('core', include('core.urls')),
]
但是,当我通过命令“ python manage.py runserver”运行应用程序时,出现错误:
ImportError:SimpleMiddleware看起来不像模块路径
您知道我在做什么错吗?
如果您想查看完整的代码,请单击此处: https://bitbucket.org/MATAN_BL/djangotry/src/master/app/
答案 0 :(得分:1)
您需要中间件的完整路径,并假设您给出的结构很可能是app.SimpleMiddleware.SimpleMiddleware
MIDDLEWARE = (
'app.SimpleMiddleware.SimpleMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)