我正在尝试在我的自定义中间件中向我的请求变量添加变量。后来我想从我的视图中访问该变量。以下是相关内容:
middleware.py
class DomainInterceptMiddleware(object):
def process_request(self, request):
request.myvar = 'whatever'
settings.py - 上面添加了CommonMiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'page.middleware.DomainInterceptMiddleware', #
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
views.py
def index(request):
output = request.myvar
return HttpResponse(output)
但是,在尝试访问/index
时,我收到此错误
File "/path/to/views.py", line 32, in index
output = request.myvar
AttributeError: 'WSGIRequest' object has no attribute 'myvar'
我哪里错了?
答案 0 :(得分:3)
您当前的中间件类是针对旧MIDDLEWARE_CLASSES
设置编写的。
您正在使用MIDDLEWARE
设置,因此您需要编写new-style middleware(Django 1.10+)。
如果您需要向后兼容,可以使用django.utils.deprecation
中的MiddlewareMixin
。
from django.utils.deprecation.MiddlewareMixin
class DomainInterceptMiddleware(MiddlewareMixin):
def process_request(self, request):
request.myvar = 'whatever'
或者您可以将其转换为新式中间件。
class DomainInterceptMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.myvar = 'whatever'
response = self.get_response(request)
return response
有关详细信息,请参阅writing your own middleware上的文档。