Accessing the current view class instance in Django middleware

There is no built-in way to do this, but here is a solution given to me by a kindly user on the django-users mailing list. I'm reposting his suggestion here in case anyone else is trying to do the same thing.

This is useful if:

  1. you want to identify properties of the current view in your middleware and perform processing accordingly, and;
  2. for various reasons you don't want to use mixins or decorators to accomplish similar results.

This inspects the view_func object passed to the process_view() middleware hook and determines and imports the the appropriate view class.

from myutils import get_class

def process_view(self, request, view_func, view_args, view_kwargs):
        view = get_class(view_func.__module__, view_func.__name__)

Then your get_class() definition:

from django.utils import importlib

def get_class(module_name, cls_name):
        module = importlib.import_module(module_name)
    except ImportError:
        raise ImportError('Invalid class path: {}'.format(module_name))
        cls = getattr(module, cls_name)
    except AttributeError:
        raise ImportError('Invalid class name: {}'.format(cls_name))
        return cls