2

I am trying to add a variable to my request variable in my custom middleware. Later I want to access that variable from my view. Here are the relevant bits:

middleware.py

class DomainInterceptMiddleware(object):
    def process_request(self, request):
        request.myvar = 'whatever'

settings.py - Added this above 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)

However, on trying to access /index, I get this error

  File "/path/to/views.py", line 32, in index
    output = request.myvar
AttributeError: 'WSGIRequest' object has no attribute 'myvar'

Where am I going wrong?

S B
  • 8,134
  • 10
  • 54
  • 108

1 Answers1

4

Your current middleware class is written for the old MIDDLEWARE_CLASSES setting.

You are using the MIDDLEWARE setting, so you need to write a new-style middleware (Django 1.10+).

If you need backwards compatibility, you could use the MiddlewareMixin from django.utils.deprecation.

from django.utils.deprecation.MiddlewareMixin

class DomainInterceptMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.myvar = 'whatever'

Or you can convert it to a new-style middleware.

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

See the docs on writing your own middleware for more info.

Alasdair
  • 298,606
  • 55
  • 578
  • 516