title: Django: How to access session_key in middleware
body: <p>I'm unable to access the <code>session_key</code> in my custom Django middleware. I try to access it using:</p>
  
  <pre><code>session = Session.objects.get(pk=request.session._session_key)
  </code></pre>
  
  <p>or</p>
  
  <pre><code>session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
  session = Session.objects.get(pk=session_key)
  </code></pre>
  
  <p>I get the error:</p>
  
  <pre><code>Session matching query does not exist.
  </code></pre>
  
  <p>I have put my middleware at the end of <code>MIDDLEWARE_CLASSES</code> and after <code>django.contrib.sessions.middleware.SessionMiddleware</code> in my <code>settings.py</code> file.</p>
  
  <p>I can set session keys in the middleware, but it appears as if the session_key is only generated/accessible after the full page is displayed. Because when the page is displayed for the first time <code>{{ request.session.session_key }}</code> returns <code>None</code> in my template. When I refresh the page I get to see the <code>session_key</code>. Any tips on how I can access the <code>session_key</code> are very welcome.</p>