title: Accessing the current view class instance in Django middleware
body: <p><strong>Question:</strong></p>
  
  <p>I'm trying to access an attribute of the view instance in the middleware layer.</p>
  
  <p>For example, given a class-based view like this:</p>
  
  <pre><code># views.py
  class MyView(View):
      my_attribute = 'something'
  </code></pre>
  
  <p>I'd love to be able to get a handle on <code>my_attribute</code> in the middleware by doing something like this:</p>
  
  <pre><code># middleware.py
  def process_view(self, request, view_func, view_args, view_kwargs):
      my_attribute = request.view.my_attribute
  </code></pre>
  
  <p>Of course, this does not work because Django doesn't expose the view instance through the request object.  Is there a way to get this accomplished?</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p><strong>My first attempt:</strong></p>
  
  <p>I initially figured that the <code>process_view()</code> method might be a good place to do this.  Unfortunately, the <code>view_func</code> argument it receives contains a function -- the output of <code>MyView.as_view()</code> -- rather than the view instance itself.  From the <a href="https://docs.djangoproject.com/en/dev/topics/http/middleware/#process-view" rel="noreferrer">Django docs</a>:</p>
  
  <blockquote>
    <p><strong>process_view(self, request, view_func, view_args, view_kwargs)</strong></p>
    
    <p>...view_func is the Python function that Django is about to use. (It’s the actual function
    object, not the name of the function as a string.)...</p>
  </blockquote>
  
  <hr>
  
  <p><strong>My second attempt:</strong></p>
  
  <p>A handle to the view instance is available in <code>process_template_response()</code> method, but it's pretty awkward, and, in any case, I'd like to be able to work with <code>my_attribute</code> at an earlier point in the middleware stack.  But this does work:</p>
  
  <pre><code>def process_template_response(self, request, response):
      my_attribute = response.context_data['view'].my_attribute
  </code></pre>